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
d48a29048e60893a67950979678a97d13a7bc581
src/babel-streams-xz.ads
src/babel-streams-xz.ads
----------------------------------------------------------------------- -- babel-Streams-xz -- XZ/LZMA stream management -- 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. ----------------------------------------------------------------------- private with Lzma.Base; -- == Compression and Decompression Stream == -- The <tt>Babel.Streams.XZ</tt> package provides a compression decompression stream on top -- of the <tt>LZMA</tt> library. package Babel.Streams.XZ is type Stream_Type is new Babel.Streams.Stream_Type with private; type Stream_Access is access all Stream_Type'Class; -- Read the data stream as much as possible and return the result in a buffer. -- The buffer is owned by the stream and need not be released. The same buffer may -- or may not be returned by the next <tt>Read</tt> operation. -- A null buffer is returned when the end of the data stream is reached. overriding procedure Read (Stream : in out Stream_Type; Buffer : out Babel.Files.Buffers.Buffer_Access); -- Write the buffer in the data stream. overriding procedure Write (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access); -- Flush the data stream. overriding procedure Flush (Stream : in out Stream_Type); -- Close the data stream. overriding procedure Close (Stream : in out Stream_Type); -- Prepare to read again the data stream from the beginning. overriding procedure Rewind (Stream : in out Stream_Type); private type Stream_Type is new Babel.Streams.Stream_Type with record Context : Lzma.Base.lzma_stream := Lzma.Base.LZMA_STREAM_INIT; Action : Lzma.Base.lzma_action := Lzma.Base.LZMA_RUN; end record; end Babel.Streams.XZ;
----------------------------------------------------------------------- -- babel-Streams-xz -- XZ/LZMA stream management -- 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. ----------------------------------------------------------------------- private with Lzma.Base; -- == Compression and Decompression Stream == -- The <tt>Babel.Streams.XZ</tt> package provides a compression decompression stream on top -- of the <tt>LZMA</tt> library. package Babel.Streams.XZ is type Stream_Type is new Babel.Streams.Stream_Type with private; type Stream_Access is access all Stream_Type'Class; -- Read the data stream as much as possible and return the result in a buffer. -- The buffer is owned by the stream and need not be released. The same buffer may -- or may not be returned by the next <tt>Read</tt> operation. -- A null buffer is returned when the end of the data stream is reached. overriding procedure Read (Stream : in out Stream_Type; Buffer : out Babel.Files.Buffers.Buffer_Access); -- Write the buffer in the data stream. overriding procedure Write (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access); -- Flush the data stream. overriding procedure Flush (Stream : in out Stream_Type); -- Close the data stream. overriding procedure Close (Stream : in out Stream_Type); -- Prepare to read again the data stream from the beginning. overriding procedure Rewind (Stream : in out Stream_Type); private type Stream_Type is new Babel.Streams.Stream_Type with record Input : Babel.Streams.Stream_Access; Output : Babel.Streams.Stream_Access; Context : aliased Lzma.Base.lzma_stream := Lzma.Base.LZMA_STREAM_INIT; Action : Lzma.Base.lzma_action := Lzma.Base.LZMA_RUN; Buffer : Babel.Files.Buffers.Buffer_Access; end record; end Babel.Streams.XZ;
Update the Stream type to store the input/output stream and action state
Update the Stream type to store the input/output stream and action state
Ada
apache-2.0
stcarrez/babel
bf68258b24f29519465d49fd238c2d19469b551d
mat/src/events/mat-events-probes.adb
mat/src/events/mat-events-probes.adb
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; 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; 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 Interfaces.Unsigned_64; 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 Frame.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 => Frame.Thread := 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; Frame.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32); Frame.Time := Frame.Time or Interfaces.Unsigned_64 (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); 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; -- ------------------------------ -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. -- ------------------------------ procedure Read_Headers (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is begin Client.Read_Event_Definitions (Msg); Client.Frame := new MAT.Events.Frame_Info (512); exception when E : others => Log.Error ("Exception while reading headers ", E); end Read_Headers; end MAT.Events.Probes;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; 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 Interfaces.Unsigned_64; 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 Frame.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 => Frame.Thread := 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; Frame.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32); Frame.Time := Frame.Time or Interfaces.Unsigned_64 (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); 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; -- ------------------------------ -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. -- ------------------------------ procedure Read_Headers (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is begin Client.Read_Event_Definitions (Msg); Client.Frame := new MAT.Events.Frame_Info (512); exception when E : others => Log.Error ("Exception while reading headers ", E); end Read_Headers; end MAT.Events.Probes;
Create the root frame when the probe manager is created
Create the root frame when the probe manager is created
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
81f4188f3aae3cd83e63bb2817ea02475ce17222
regtests/wiki-tests.ads
regtests/wiki-tests.ads
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package Wiki.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test_Case with record Writer : Integer; Name : Ada.Strings.Unbounded.Unbounded_String; File : Ada.Strings.Unbounded.Unbounded_String; Expect : Ada.Strings.Unbounded.Unbounded_String; Result : Ada.Strings.Unbounded.Unbounded_String; Source : Wiki.Wiki_Syntax; Format : Wiki.Wiki_Syntax; Is_Html : Boolean := False; Is_Cvt : Boolean := False; end record; type Test_Case_Access is access all Test; -- Test case name overriding function Name (T : Test) return Util.Tests.Message_String; -- Perform the test. overriding procedure Run_Test (T : in out Test); -- Test rendering a wiki text in HTML or text. procedure Test_Render (T : in out Test); end Wiki.Tests;
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package Wiki.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test_Case with record Writer : Integer; Name : Ada.Strings.Unbounded.Unbounded_String; File : Ada.Strings.Unbounded.Unbounded_String; Expect : Ada.Strings.Unbounded.Unbounded_String; Result : Ada.Strings.Unbounded.Unbounded_String; Collect : Ada.Strings.Unbounded.Unbounded_String; Expect_Collect : Ada.Strings.Unbounded.Unbounded_String; Source : Wiki.Wiki_Syntax; Format : Wiki.Wiki_Syntax; Is_Html : Boolean := False; Is_Cvt : Boolean := False; end record; type Test_Case_Access is access all Test; -- Test case name overriding function Name (T : Test) return Util.Tests.Message_String; -- Perform the test. overriding procedure Run_Test (T : in out Test); -- Test rendering a wiki text in HTML or text. procedure Test_Render (T : in out Test); end Wiki.Tests;
Add Collect and Expect_Collect members in the test record
Add Collect and Expect_Collect members in the test record
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b1d9a54666660eda5b876ecdb0edb85a39705f20
regtests/ado-tests.adb
regtests/ado-tests.adb
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Ada.Exceptions; use ADO.Statements; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; T.Fail ("Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.Session_Error => Assert_Has_Message (T, E); end; begin DB.Commit; T.Fail ("Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.Session_Error => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use type ADO.Sessions.Connection_Status; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin T.Assert (DB.Get_Status = ADO.Sessions.OPEN, "The database connection is open"); Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Nullable_String; begin Name.Is_Null := False; for I in 1 .. 127 loop Append (Name.Value, Character'Val (I)); end loop; Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name.Value), String '(Usr2.Get_Name), "Invalid name inserted for user"); Usr2.Set_Name (ADO.Null_String); Usr2.Save (DB); User.Load (DB, Usr2.Get_Id); T.Assert (User.Get_Name.Is_Null, "Name must be null after save"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); declare Content : Ada.Streams.Stream_Element_Array (1 .. 10); Img3 : Regtests.Images.Model.Image_Ref; begin for I in Content'Range loop Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30); end loop; Data := ADO.Create_Blob (Content); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)"); T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small"); DB.Begin_Transaction; Img3.Set_Image (Data); Img3.Set_Create_Date (Ada.Calendar.Clock); Img3.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img3.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); Img2.Set_Image (ADO.Null_Blob); Img2.Save (DB); DB.Commit; end; end Test_Blob; -- ------------------------------ -- Test the To_Object and To_Identifier operations. -- ------------------------------ procedure Test_Identifier_To_Object (T : in out Test) is Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER); begin T.Assert (Util.Beans.Objects.Is_Null (Val), "To_Object must return null for ADO.NO_IDENTIFIER"); T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER, "To_Identifier must return ADO.NO_IDENTIFIER for null"); Val := ADO.Utils.To_Object (1); T.Assert (not Util.Beans.Objects.Is_Null (Val), "To_Object must not return null for a valid Identifier"); T.Assert (ADO.Utils.To_Identifier (Val) = 1, "To_Identifier must return the correct identifier"); end Test_Identifier_To_Object; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier", Test_Identifier_To_Object'Access); end Add_Tests; end ADO.Tests;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018, 2019, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Regtests.Comments; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Ada.Exceptions; use ADO.Statements; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; T.Fail ("Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.Session_Error => Assert_Has_Message (T, E); end; begin DB.Commit; T.Fail ("Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.Session_Error => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use type ADO.Sessions.Connection_Status; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin T.Assert (DB.Get_Status = ADO.Sessions.OPEN, "The database connection is open"); Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Nullable_String; begin Name.Is_Null := False; for I in 1 .. 127 loop Append (Name.Value, Character'Val (I)); end loop; Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name.Value), String '(Usr2.Get_Name), "Invalid name inserted for user"); Usr2.Set_Name (ADO.Null_String); Usr2.Save (DB); User.Load (DB, Usr2.Get_Id); T.Assert (User.Get_Name.Is_Null, "Name must be null after save"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); declare Content : Ada.Streams.Stream_Element_Array (1 .. 10); Img3 : Regtests.Images.Model.Image_Ref; begin for I in Content'Range loop Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30); end loop; Data := ADO.Create_Blob (Content); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)"); T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small"); DB.Begin_Transaction; Img3.Set_Image (Data); Img3.Set_Create_Date (Ada.Calendar.Clock); Img3.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img3.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); Img2.Set_Image (ADO.Null_Blob); Img2.Save (DB); DB.Commit; end; end Test_Blob; -- ------------------------------ -- Test database reload. -- ------------------------------ procedure Test_Reload (T : in out Test) is User : Regtests.Simple.Model.User_Ref; Cmt : Regtests.Comments.Comment_Ref; begin -- Create an object and comment within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe"); User.Set_Value (0); User.Save (S); Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe")); Cmt.Set_User (User); Cmt.Set_Entity_Id (2); Cmt.Set_Entity_Type (1); Cmt.Set_Date (Ada.Calendar.Clock); Cmt.Save (S); S.Commit; end; -- Update the comment. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; C2 : Regtests.Comments.Comment_Ref; Updated : Boolean; Found : Boolean; begin S.Begin_Transaction; C2.Load (S, Cmt.Get_Id, Found); T.Assert (Found, "Comment must be loaded"); C2.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A updated comment from Joe")); C2.Save (S); S.Commit; Cmt.Reload (S, Updated); T.Assert (Updated, "Reload must return Update=true"); Cmt.Reload (S, Updated); T.Assert (not Updated, "Reload must return Update=false"); C2.Reload (S, Updated); T.Assert (not Updated, "Reload must return Update=false"); end; end Test_Reload; -- ------------------------------ -- Test the To_Object and To_Identifier operations. -- ------------------------------ procedure Test_Identifier_To_Object (T : in out Test) is Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER); begin T.Assert (Util.Beans.Objects.Is_Null (Val), "To_Object must return null for ADO.NO_IDENTIFIER"); T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER, "To_Identifier must return ADO.NO_IDENTIFIER for null"); Val := ADO.Utils.To_Object (1); T.Assert (not Util.Beans.Objects.Is_Null (Val), "To_Object must not return null for a valid Identifier"); T.Assert (ADO.Utils.To_Identifier (Val) = 1, "To_Identifier must return the correct identifier"); end Test_Identifier_To_Object; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier", Test_Identifier_To_Object'Access); Caller.Add_Test (Suite, "Test Object.Reload", Test_Reload'Access); end Add_Tests; end ADO.Tests;
Implement Test_Reload and register the new test for execution
Implement Test_Reload and register the new test for execution
Ada
apache-2.0
stcarrez/ada-ado
14e403e0fd6abee52f4fe1b38b9ee79b1c860963
mat/src/mat-readers.ads
mat/src/mat-readers.ads
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with System; with Util.Properties; with MAT.Types; with MAT.Events; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access Buffer_Type; type Message is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; ----------------- -- Abstract servant definition ----------------- -- The Servant is a small proxy that binds the specific message -- handlers to the client specific dispatcher. type Reader_Base is abstract tagged limited private; type Reader_Access is access all Reader_Base'Class; procedure Dispatch (For_Servant : in out Reader_Base; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out Message) is abstract; -- Dispatch the message -- procedure Bind (For_Servant : in out Reader_Base) is abstract; -- Bind the servant with the object adapter to register the -- events it recognizes. This is called once we have all the -- information about the structures of events that we can -- receive. ----------------- -- Ipc Client Manager ----------------- -- The Manager is a kind of object adapter. It registers a collection -- of servants and dispatches incomming messages to those servants. type Manager_Base is tagged limited private; type Manager is access all Manager_Base'Class; -- Register the reader 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_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message); private type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN); type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Size : Natural; Total : Natural; Endian : Endian_Type := LITTLE_ENDIAN; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; use type MAT.Types.Uint16; package Reader_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Message_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is tagged limited record Readers : Reader_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; end record; -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message); -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message); end MAT.Readers;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with System; with Util.Properties; with MAT.Types; with MAT.Events; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access all Buffer_Type; type Message is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; ----------------- -- Abstract servant definition ----------------- -- The Servant is a small proxy that binds the specific message -- handlers to the client specific dispatcher. type Reader_Base is abstract tagged limited private; type Reader_Access is access all Reader_Base'Class; procedure Dispatch (For_Servant : in out Reader_Base; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out Message) is abstract; -- Dispatch the message -- procedure Bind (For_Servant : in out Reader_Base) is abstract; -- Bind the servant with the object adapter to register the -- events it recognizes. This is called once we have all the -- information about the structures of events that we can -- receive. ----------------- -- Ipc Client Manager ----------------- -- The Manager is a kind of object adapter. It registers a collection -- of servants and dispatches incomming messages to those servants. type Manager_Base is tagged limited private; type Manager is access all Manager_Base'Class; -- Register the reader 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_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message); private type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN); type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Size : Natural; Total : Natural; Endian : Endian_Type := LITTLE_ENDIAN; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; use type MAT.Types.Uint16; package Reader_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Message_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is tagged limited record Readers : Reader_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; end record; -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message); -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message); end MAT.Readers;
Fix the Buffer_Ptr access type
Fix the Buffer_Ptr access type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
efb7f8fa928b2411b3fdbf26dde87220e7545e79
mat/regtests/mat-readers-tests.adb
mat/regtests/mat-readers-tests.adb
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Test_Caller; with MAT.Readers.Files; package body MAT.Readers.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Readers.Read_File", Test_Read_File'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/file-v1.dat"); Reader : MAT.Readers.Files.File_Reader_Type; begin Reader.Open (Path); Reader.Read_All; end Test_Read_File; end MAT.Readers.Tests;
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Test_Caller; with MAT.Readers.Streams.Files; package body MAT.Readers.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Readers.Read_File", Test_Read_File'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/file-v1.dat"); Reader : MAT.Readers.Streams.Files.File_Reader_Type; begin Reader.Open (Path); Reader.Read_All; end Test_Read_File; end MAT.Readers.Tests;
Fix compilation of unit test
Fix compilation of unit test
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
82082bcfe8f5f9e069eeaf62b2f150739ea1b31c
src/ado-connections.adb
src/ado-connections.adb
----------------------------------------------------------------------- -- ado-connections -- Database connections -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Exceptions; package body ADO.Connections is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Connections"); type Driver_Array_Access is array (Driver_Index) of Driver_Access; Driver_List : Driver_Array_Access; -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Get the driver index that corresponds to the driver for this database connection string. -- ------------------------------ function Get_Driver (Config : in Configuration) return Driver_Index is Name : constant String := Config.Get_Driver; Driver : constant Driver_Access := Get_Driver (Name); begin if Driver = null then raise ADO.Configs.Connection_Error with "Database driver '" & Name & "' not found"; else return Driver.Get_Driver_Index; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is Driver : Driver_Access; Log_URI : constant String := Config.Get_Log_URI; begin Driver := Get_Driver (Config.Get_Driver); if Driver = null then Log.Error ("No driver found for connection {0}", Log_URI); raise ADO.Configs.Connection_Error with "Data source is not initialized: driver '" & Config.Get_Driver & "' not found"; end if; Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Log_URI); raise; end Create_Connection; -- ------------------------------ -- Get the database driver index. -- ------------------------------ function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is Driver : constant Driver_Access := Database_Connection'Class (Database).Get_Driver; begin return Driver.Get_Driver_Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); for I in Driver_List'Range loop if Driver_List (I) = Driver then return; end if; if Driver_List (I) = null then Driver_List (I) := Driver; Driver.Index := I; return; end if; end loop; Log.Error ("The ADO driver table is full: increase ADO.Configs.MAX_DRIVER"); end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin if not ADO.Configs.Is_On (ADO.Configs.DYNAMIC_DRIVER_LOAD) then Log.Warn ("Dynamic loading of driver '{0}' is disabled", Name); return; end if; Log.Debug ("Loading driver '{0}' from {1}", Name, Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Log.Info ("Initialising driver {0}", Lib); Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Debug ("Get driver {0}", Name); if Name'Length = 0 then return null; end if; for Retry in 0 .. 1 loop if Retry = 1 then Load_Driver (Name); end if; for D of Driver_List loop exit when D = null; if Name = D.Name.all then return D; end if; end loop; end loop; return null; end Get_Driver; end ADO.Connections;
----------------------------------------------------------------------- -- ado-connections -- Database connections -- Copyright (C) 2010 - 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Exceptions; package body ADO.Connections is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Connections"); type Driver_Array_Access is array (Driver_Index) of Driver_Access; Driver_List : Driver_Array_Access; -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Get the driver index that corresponds to the driver for this database connection string. -- ------------------------------ function Get_Driver (Config : in Configuration) return Driver_Index is Name : constant String := Config.Get_Driver; Driver : constant Driver_Access := Get_Driver (Name); begin if Driver = null then raise ADO.Configs.Connection_Error with "Database driver '" & Name & "' not found"; else return Driver.Get_Driver_Index; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is Driver : Driver_Access; Log_URI : constant String := Config.Get_Log_URI; begin Driver := Get_Driver (Config.Get_Driver); if Driver = null then Log.Error ("No driver found for connection {0}", Log_URI); raise ADO.Configs.Connection_Error with "Data source is not initialized: driver '" & Config.Get_Driver & "' not found"; end if; Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Log_URI); raise; end Create_Connection; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); for I in Driver_List'Range loop if Driver_List (I) = Driver then return; end if; if Driver_List (I) = null then Driver_List (I) := Driver; Driver.Index := I; return; end if; end loop; Log.Error ("The ADO driver table is full: increase ADO.Configs.MAX_DRIVER"); end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin if not ADO.Configs.Is_On (ADO.Configs.DYNAMIC_DRIVER_LOAD) then Log.Warn ("Dynamic loading of driver '{0}' is disabled", Name); return; end if; Log.Debug ("Loading driver '{0}' from {1}", Name, Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Log.Info ("Initialising driver {0}", Lib); Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Debug ("Get driver {0}", Name); if Name'Length = 0 then return null; end if; for Retry in 0 .. 1 loop if Retry = 1 then Load_Driver (Name); end if; for D of Driver_List loop exit when D = null; if Name = D.Name.all then return D; end if; end loop; end loop; return null; end Get_Driver; end ADO.Connections;
Remove unused Get_Driver_Index function
Remove unused Get_Driver_Index function
Ada
apache-2.0
stcarrez/ada-ado
7ca1f6b9cfb909d7774bd59e7a2dc285074e54fe
awa/plugins/awa-storages/src/awa-storages-services.adb
awa/plugins/awa-storages/src/awa-storages-services.adb
----------------------------------------------------------------------- -- awa-storages-services -- Storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Objects; with ADO.Queries; with ADO.Statements; with ADO.Sessions.Entities; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Permissions; package body AWA.Storages.Services is use AWA.Services; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Services"); -- ------------------------------ -- Get the persistent store that manages the data represented by <tt>Data</tt>. -- ------------------------------ function Get_Store (Service : in Storage_Service; Data : in AWA.Storages.Models.Storage_Ref'Class) return AWA.Storages.Stores.Store_Access is begin return Service.Stores (Data.Get_Storage); end Get_Store; -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Storage_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); Service.Stores (AWA.Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access; end Initialize; -- ------------------------------ -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. -- ------------------------------ procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Data : in ASF.Parts.Part'Class; Storage : in AWA.Storages.Models.Storage_Type) is begin Storage_Service'Class (Service).Save (Into, Data.Get_Local_Filename, Storage); end Save; -- ------------------------------ -- Save the file pointed to by the <b>Path</b> string in the storage -- object represented by <b>Into</b> and managed by the storage service. -- ------------------------------ procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String; Storage : in AWA.Storages.Models.Storage_Type) is use type AWA.Storages.Models.Storage_Type; use type Stores.Store_Access; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Workspace : AWA.Workspaces.Models.Workspace_Ref; Store : Stores.Store_Access; begin Log.Info ("Save {0} in storage space", Path); Into.Set_Storage (Storage); Store := Storage_Service'Class (Service).Get_Store (Into); if Store = null then Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage)); end if; if not Into.Is_Null then Workspace := AWA.Workspaces.Models.Workspace_Ref (Into.Get_Workspace); end if; if Workspace.Is_Null then AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace); Into.Set_Workspace (Workspace); end if; -- Check that the user has the create storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Storage.Permission, Entity => Workspace.Get_Id); Ctx.Start; if not Into.Is_Inserted then Into.Set_Create_Date (Ada.Calendar.Clock); end if; Store.Save (DB, Into, Path); Into.Save (DB); Ctx.Commit; end Save; -- Load the storage content identified by <b>From</b> in a local file -- that will be identified by <b>Into</b>. procedure Load (Service : in Storage_Service; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Models.Store_Local_Ref'Class) is begin null; end Load; -- ------------------------------ -- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>. -- Raises the <b>NOT_FOUND</b> exception if there is no such storage. -- ------------------------------ procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Into : out ADO.Blob_Ref) is pragma Unreferenced (Service); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Statements.Query_Statement := DB.Create_Statement (Models.Query_Storage_Get_Data); begin Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE'Access, DB); Query.Execute; Into := Query.Get_Result_Blob; end Load; -- Load the storage content into a file. If the data is not stored in a file, a temporary -- file is created with the data content fetched from the store (ex: the database). -- The `Mode` parameter indicates whether the file will be read or written. -- The `Expire` parameter allows to control the expiration of the temporary file. procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Into : out AWA.Storages.Models.Store_Local_Ref; Mode : in Read_Mode := READ; Expire : in Expire_Type := ONE_DAY) is use type Stores.Store_Access; use type Models.Storage_Type; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.Queries.Context; Found : Boolean; Storage : AWA.Storages.Models.Storage_Ref; Store : Stores.Store_Access; begin if Mode = READ then Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Local); Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); Into.Find (DB, Query, Found); if Found then return; end if; end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Storage); Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); Storage.Find (DB, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; if Storage.Get_Storage = AWA.Storages.Models.FILE then Into.Set_Path (String '(Storage.Get_Uri)); return; end if; Store := Storage_Service'Class (Service).Get_Store (Storage); Store.Load (Session => DB, From => Storage, Into => Into.Get_Path); end Load; -- ------------------------------ -- Deletes the storage instance. -- ------------------------------ procedure Delete (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Service); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Id : constant ADO.Identifier := ADO.Objects.Get_Value (Storage.Get_Key); begin Log.Info ("Delete storage {0}", ADO.Identifier'Image (Id)); -- Check that the user has the delete storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission, Entity => Id); Ctx.Start; Storage.Delete (DB); Ctx.Commit; end Delete; -- ------------------------------ -- Deletes the storage instance. -- ------------------------------ procedure Delete (Service : in Storage_Service; Storage : in ADO.Identifier) is use type Stores.Store_Access; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); S : AWA.Storages.Models.Storage_Ref; Query : ADO.Statements.Query_Statement := DB.Create_Statement (AWA.Storages.Models.Query_Storage_Delete_Local); Store : Stores.Store_Access; begin Log.Info ("Delete storage {0}", ADO.Identifier'Image (Storage)); -- Check that the user has the delete storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission, Entity => Storage); Ctx.Start; S.Load (Id => Storage, Session => DB); Store := Storage_Service'Class (Service).Get_Store (S); if Store = null then Log.Error ("There is no store associated with storage item {0}", ADO.Identifier'Image (Storage)); else Store.Delete (DB, S); end if; -- Delete the local storage instances. Query.Bind_Param ("store_id", Storage); Query.Execute; S.Delete (DB); Ctx.Commit; end Delete; end AWA.Storages.Services;
----------------------------------------------------------------------- -- awa-storages-services -- Storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Objects; with ADO.Queries; with ADO.Statements; with ADO.Sessions.Entities; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Permissions; package body AWA.Storages.Services is use AWA.Services; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Services"); -- ------------------------------ -- Get the persistent store that manages the data represented by <tt>Data</tt>. -- ------------------------------ function Get_Store (Service : in Storage_Service; Data : in AWA.Storages.Models.Storage_Ref'Class) return AWA.Storages.Stores.Store_Access is begin return Service.Stores (Data.Get_Storage); end Get_Store; -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Storage_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); Service.Stores (AWA.Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access; end Initialize; -- ------------------------------ -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. -- ------------------------------ procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Data : in ASF.Parts.Part'Class; Storage : in AWA.Storages.Models.Storage_Type) is begin Storage_Service'Class (Service).Save (Into, Data.Get_Local_Filename, Storage); end Save; -- ------------------------------ -- Save the file pointed to by the <b>Path</b> string in the storage -- object represented by <b>Into</b> and managed by the storage service. -- ------------------------------ procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String; Storage : in AWA.Storages.Models.Storage_Type) is use type AWA.Storages.Models.Storage_Type; use type Stores.Store_Access; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Workspace : AWA.Workspaces.Models.Workspace_Ref; Store : Stores.Store_Access; begin Log.Info ("Save {0} in storage space", Path); Into.Set_Storage (Storage); Store := Storage_Service'Class (Service).Get_Store (Into); if Store = null then Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage)); end if; if not Into.Is_Null then Workspace := AWA.Workspaces.Models.Workspace_Ref (Into.Get_Workspace); end if; if Workspace.Is_Null then AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace); Into.Set_Workspace (Workspace); end if; -- Check that the user has the create storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Storage.Permission, Entity => Workspace.Get_Id); Ctx.Start; if not Into.Is_Inserted then Into.Set_Create_Date (Ada.Calendar.Clock); end if; Into.Save (DB); Store.Save (DB, Into, Path); Into.Save (DB); Ctx.Commit; end Save; -- Load the storage content identified by <b>From</b> in a local file -- that will be identified by <b>Into</b>. procedure Load (Service : in Storage_Service; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Models.Store_Local_Ref'Class) is begin null; end Load; -- ------------------------------ -- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>. -- Raises the <b>NOT_FOUND</b> exception if there is no such storage. -- ------------------------------ procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Into : out ADO.Blob_Ref) is pragma Unreferenced (Service); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Statements.Query_Statement := DB.Create_Statement (Models.Query_Storage_Get_Data); begin Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE'Access, DB); Query.Execute; Into := Query.Get_Result_Blob; end Load; -- Load the storage content into a file. If the data is not stored in a file, a temporary -- file is created with the data content fetched from the store (ex: the database). -- The `Mode` parameter indicates whether the file will be read or written. -- The `Expire` parameter allows to control the expiration of the temporary file. procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Into : out AWA.Storages.Models.Store_Local_Ref; Mode : in Read_Mode := READ; Expire : in Expire_Type := ONE_DAY) is use type Stores.Store_Access; use type Models.Storage_Type; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.Queries.Context; Found : Boolean; Storage : AWA.Storages.Models.Storage_Ref; Store : Stores.Store_Access; begin if Mode = READ then Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Local); Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); Into.Find (DB, Query, Found); if Found then return; end if; end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Storage); Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); Storage.Find (DB, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; if Storage.Get_Storage = AWA.Storages.Models.FILE then Into.Set_Path (String '(Storage.Get_Uri)); return; end if; Store := Storage_Service'Class (Service).Get_Store (Storage); Store.Load (Session => DB, From => Storage, Into => Into.Get_Path); end Load; -- ------------------------------ -- Deletes the storage instance. -- ------------------------------ procedure Delete (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Service); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Id : constant ADO.Identifier := ADO.Objects.Get_Value (Storage.Get_Key); begin Log.Info ("Delete storage {0}", ADO.Identifier'Image (Id)); -- Check that the user has the delete storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission, Entity => Id); Ctx.Start; Storage.Delete (DB); Ctx.Commit; end Delete; -- ------------------------------ -- Deletes the storage instance. -- ------------------------------ procedure Delete (Service : in Storage_Service; Storage : in ADO.Identifier) is use type Stores.Store_Access; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); S : AWA.Storages.Models.Storage_Ref; Query : ADO.Statements.Query_Statement := DB.Create_Statement (AWA.Storages.Models.Query_Storage_Delete_Local); Store : Stores.Store_Access; begin Log.Info ("Delete storage {0}", ADO.Identifier'Image (Storage)); -- Check that the user has the delete storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission, Entity => Storage); Ctx.Start; S.Load (Id => Storage, Session => DB); Store := Storage_Service'Class (Service).Get_Store (S); if Store = null then Log.Error ("There is no store associated with storage item {0}", ADO.Identifier'Image (Storage)); else Store.Delete (DB, S); end if; -- Delete the local storage instances. Query.Bind_Param ("store_id", Storage); Query.Execute; S.Delete (DB); Ctx.Commit; end Delete; end AWA.Storages.Services;
Save the file before invoking the store specific save operation
Save the file before invoking the store specific save operation
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
aa8080f98eeea828efc931c0dff7ad6080d8685b
src/cupcake-windows.adb
src/cupcake-windows.adb
-- The Cupcake GUI Toolkit -- (c) Kristian Klomsten Skordal 2012 <[email protected]> -- Report bugs and issues on <http://github.com/skordal/cupcake/issues> with Ada.Text_IO; with Ada.Unchecked_Deallocation; with Interfaces.C.Strings; package body Cupcake.Windows is package C renames Interfaces.C; -- Available backend functions: function Backend_Window_Create(Parent : in Backend_Data_Ptr; Width, Height : in Positive) return Backend_Data_Ptr; procedure Backend_Window_Finalize(Window : in Backend_Data_Ptr); procedure Backend_Window_Set_Title(Window : in Backend_Data_Ptr; Title : in C.Strings.chars_ptr); function Backend_Window_Get_ID(Window : in Backend_Data_Ptr) return Window_ID_Type; procedure Backend_Window_Show(Window : in Backend_Data_Ptr); procedure Backend_Window_Close(Window : in Backend_Data_Ptr); pragma Import(C, Backend_Window_Create, "backend_window_create"); pragma Import(C, Backend_Window_Finalize, "backend_window_finalize"); pragma Import(C, Backend_Window_Set_Title, "backend_window_set_title"); pragma Import(C, Backend_Window_Get_ID, "backend_window_get_id"); pragma Import(C, Backend_Window_Show, "backend_window_show"); pragma import(C, Backend_Window_Close, "backend_window_close"); -- Creates a new window: function New_Window(Width, Height : in Positive; Title : in String) return Window is Size : constant Primitives.Dimension := (Width, Height); begin return New_Window(Size, Title); end New_Window; -- Creates a new window: function New_Window(Size : in Primitives.Dimension; Title : in String) return Window is Retval : constant Window := new Window_Record; C_Title : C.Strings.chars_ptr := C.Strings.New_String(Title); begin Retval.Backend_Data := Backend_Window_Create(System.Null_Address, Size.Width, Size.Height); Retval.Window_ID := Backend_Window_Get_ID(Retval.Backend_Data); Retval.Size := Size; Backend_Window_Set_Title(Retval.Backend_Data, C_Title); C.Strings.Free(C_Title); Retval.Graphics_Context := Graphics.New_Context(Retval.Backend_Data, Size); Window_List.Append(Retval); return Retval; end New_Window; -- Destroys a window: procedure Destroy(Object : not null access Window_Record) is use Cupcake.Layouts; -- Deallocation procedure for window records: type Window_Access is access all Window_Record; procedure Free is new Ada.Unchecked_Deallocation(Object => Window_Record, Name => Window_Access); Win : Window_Access := Window_Access(Object); begin if Object.Layout /= null then Layouts.Destroy(Object.Layout); end if; Object.Close; Backend_Window_Finalize(Object.Backend_Data); Free(Win); end Destroy; -- Shows a window: procedure Show(This : in Window_Record'Class) is begin Backend_Window_Show(This.Backend_Data); end Show; -- Closes a window: procedure Close(This : in Window_Record'Class) is begin Backend_Window_Close(This.Backend_Data); end Close; -- Gets the window ID: function Get_ID(This : in Window_Record'Class) return Window_ID_Type is begin return This.Window_ID; end Get_ID; -- Gets the size of a window: function Get_Size(This : in Window_Record'Class) return Primitives.Dimension is begin return This.Size; end Get_Size; -- Gets the background color of a window: function Get_Background_Color(This : in Window_Record'Class) return Colors.Color is begin return This.Background_Color; end Get_Background_Color; -- Sets the background color of a window: procedure Set_Background_Color(This : out Window_Record'Class; Color : in Colors.Color) is begin This.Background_Color := Color; end Set_Background_Color; -- Sets the layout of a window: procedure Set_Layout(This : out Window_Record'Class; Layout : in Layouts.Layout) is begin This.Layout := Layout; end Set_Layout; -- Gets the layout of a window: function Get_Layout(This : in Window_Record'Class) return Layouts.Layout is begin return This.Layout; end Get_Layout; -- Expose handlers for windows: procedure Expose_Handler(This : in out Window_Record; Graphics_Context : in Graphics.Context) is use Cupcake.Layouts; Entire_Window : constant Primitives.Rectangle := ((0, 0), This.Get_Size); begin Graphics_Context.Fill(This.Get_Background_Color, Entire_Window); if This.Layout /= null then if Debug_Mode then Ada.Text_IO.Put_Line( "[Window_Record => Expose_Handler] Propagating expose event to layout"); end if; This.Layout.Expose_Handler(Graphics_Context); end if; end Expose_Handler; -- Resize handler for windows: procedure Resize_Handler(This : in out Window_Record; New_Size : in Primitives.Dimension) is use Cupcake.Layouts; begin This.Size := New_Size; This.Graphics_Context.Set_Size(New_Size); if This.Layout /= null then if Debug_Mode then Ada.Text_IO.Put_Line( "[Window_Record => Resize_Handler] Propagating resize event to layout"); end if; This.Layout.Resize_Handler(New_Size); end if; end Resize_Handler; -- Mouse event handler: function Mouse_Handler(This : in Window_Record; Mouse_Event : in Events.Mouse_Event_Record) return Boolean is begin return true; end Mouse_Handler; -- Keyboard event handler: function Keyboard_Handler(This : in Window_Record; Keyboard_Event : in Events.Keyboard_Event_Record) return Boolean is begin return true; end Keyboard_Handler; -- Window closing handler: function Window_Closing_Handler(This : in Window_Record) return Boolean is begin return true; end Window_Closing_Handler; -- Finds a window by its ID: function Find_Window_By_ID(ID : in Window_ID_Type) return Window is use Window_Lists; Window_Cursor : Cursor := Window_List.First; begin while Has_Element(Window_Cursor) loop if Element(Window_Cursor).Window_ID = ID then return Element(Window_Cursor); end if; Window_Cursor := Next(Window_Cursor); end loop; return null; end Find_Window_By_ID; -- Gets the backend specific data pointer from a window by its ID: function Get_Backend_Data_For_Window_By_ID(ID : in Window_ID_Type) return Backend_Data_Ptr is Target : constant Window := Find_Window_By_ID(ID); begin return Target.Backend_Data; end Get_Backend_Data_For_Window_By_ID; -- Posts an expose event to a window: procedure Post_Expose(ID : in Window_ID_Type) is use Cupcake.Events; Target : constant Window := Find_Window_By_ID(ID); begin if Debug_Mode then Ada.Text_IO.Put_Line("Expose event received for window" & Window_ID_Type'Image(ID)); end if; if Target = null then Ada.Text_IO.Put_Line("Invalid window ID" & Window_ID_Type'Image(ID)); else Target.Expose_Handler(Target.Graphics_Context); end if; end Post_Expose; -- Posts a resize event to a window: procedure Post_Resize(ID : in Window_ID_Type; Width, Height : in Natural) is Target : constant Window := Find_Window_By_ID(ID); begin if Debug_Mode then Ada.Text_IO.Put_Line("Resize event received for window " & Window_ID_Type'Image(ID) & " with width " & Natural'Image(Width) & " and height " & Natural'Image(Height)); end if; if Target = null then Ada.Text_IO.Put_Line("Invalid window ID" & Window_ID_Type'Image(ID)); else Target.Resize_Handler((Width, Height)); end if; end Post_Resize; -- Posts a window close event to a window: function Post_Window_Close(ID : in Window_ID_Type) return Integer is use Cupcake.Events; Target : constant Window := Find_Window_By_ID(ID); Target_Cursor : Window_Lists.Cursor := Window_List.Find(Target); Closing : Boolean := false; begin if Debug_Mode then Ada.Text_IO.Put_Line("Window close event received for window" & Window_ID_Type'Image(ID)); end if; if Target = null or not Window_Lists.Has_Element(Target_Cursor) then Ada.Text_IO.Put_Line("Invalid window ID or not visible window: " & Window_ID_Type'Image(ID)); return 0; end if; Closing := Target.Window_Closing_Handler; if Closing then Window_List.Delete(Target_Cursor); return 1; else return 0; end if; end Post_Window_Close; -- Gets the number of windows remaining: function Get_Num_Windows_Remaining return Natural is begin return Natural(Window_List.Length); end Get_Num_Windows_Remaining; end Cupcake.Windows;
-- The Cupcake GUI Toolkit -- (c) Kristian Klomsten Skordal 2012 <[email protected]> -- Report bugs and issues on <http://github.com/skordal/cupcake/issues> with Ada.Text_IO; with Ada.Unchecked_Deallocation; with Interfaces.C.Strings; package body Cupcake.Windows is package C renames Interfaces.C; -- Available backend functions: function Backend_Window_Create(Parent : in Backend_Data_Ptr; Width, Height : in Positive) return Backend_Data_Ptr; procedure Backend_Window_Finalize(Window : in Backend_Data_Ptr); procedure Backend_Window_Set_Title(Window : in Backend_Data_Ptr; Title : in C.Strings.chars_ptr); function Backend_Window_Get_ID(Window : in Backend_Data_Ptr) return Window_ID_Type; procedure Backend_Window_Show(Window : in Backend_Data_Ptr); procedure Backend_Window_Close(Window : in Backend_Data_Ptr); pragma Import(C, Backend_Window_Create, "backend_window_create"); pragma Import(C, Backend_Window_Finalize, "backend_window_finalize"); pragma Import(C, Backend_Window_Set_Title, "backend_window_set_title"); pragma Import(C, Backend_Window_Get_ID, "backend_window_get_id"); pragma Import(C, Backend_Window_Show, "backend_window_show"); pragma import(C, Backend_Window_Close, "backend_window_close"); -- Creates a new window: function New_Window(Width, Height : in Positive; Title : in String) return Window is Size : constant Primitives.Dimension := (Width, Height); begin return New_Window(Size, Title); end New_Window; -- Creates a new window: function New_Window(Size : in Primitives.Dimension; Title : in String) return Window is Retval : constant Window := new Window_Record; C_Title : C.Strings.chars_ptr := C.Strings.New_String(Title); begin Retval.Backend_Data := Backend_Window_Create(System.Null_Address, Size.Width, Size.Height); Retval.Window_ID := Backend_Window_Get_ID(Retval.Backend_Data); Retval.Size := Size; Backend_Window_Set_Title(Retval.Backend_Data, C_Title); C.Strings.Free(C_Title); Retval.Graphics_Context := Graphics.New_Context(Retval.Backend_Data, Size); Window_List.Append(Retval); return Retval; end New_Window; -- Destroys a window: procedure Destroy(Object : not null access Window_Record) is use Cupcake.Layouts; -- Deallocation procedure for window records: type Window_Access is access all Window_Record; procedure Free is new Ada.Unchecked_Deallocation(Object => Window_Record, Name => Window_Access); Win : Window_Access := Window_Access(Object); begin if Object.Layout /= null then Layouts.Destroy(Object.Layout); end if; Object.Close; Backend_Window_Finalize(Object.Backend_Data); Free(Win); end Destroy; -- Shows a window: procedure Show(This : in Window_Record'Class) is begin Backend_Window_Show(This.Backend_Data); end Show; -- Closes a window: procedure Close(This : in Window_Record'Class) is begin Backend_Window_Close(This.Backend_Data); end Close; -- Gets the window ID: function Get_ID(This : in Window_Record'Class) return Window_ID_Type is begin return This.Window_ID; end Get_ID; -- Gets the size of a window: function Get_Size(This : in Window_Record'Class) return Primitives.Dimension is begin return This.Size; end Get_Size; -- Gets the background color of a window: function Get_Background_Color(This : in Window_Record'Class) return Colors.Color is begin return This.Background_Color; end Get_Background_Color; -- Sets the background color of a window: procedure Set_Background_Color(This : out Window_Record'Class; Color : in Colors.Color) is begin This.Background_Color := Color; end Set_Background_Color; -- Sets the layout of a window: procedure Set_Layout(This : out Window_Record'Class; Layout : in Layouts.Layout) is begin This.Layout := Layout; end Set_Layout; -- Gets the layout of a window: function Get_Layout(This : in Window_Record'Class) return Layouts.Layout is begin return This.Layout; end Get_Layout; -- Expose handlers for windows: procedure Expose_Handler(This : in out Window_Record; Graphics_Context : in Graphics.Context) is use Cupcake.Layouts; Entire_Window : constant Primitives.Rectangle := ((0, 0), This.Get_Size); begin Graphics_Context.Fill(This.Get_Background_Color, Entire_Window); if This.Layout /= null then if Debug_Mode then Ada.Text_IO.Put_Line( "[Window_Record => Expose_Handler] Propagating expose event to layout"); end if; This.Layout.Expose_Handler(Graphics_Context); end if; end Expose_Handler; -- Resize handler for windows: procedure Resize_Handler(This : in out Window_Record; New_Size : in Primitives.Dimension) is use Cupcake.Layouts; begin This.Size := New_Size; This.Graphics_Context.Set_Size(New_Size); if This.Layout /= null then if Debug_Mode then Ada.Text_IO.Put_Line( "[Window_Record => Resize_Handler] Propagating resize event to layout"); end if; This.Layout.Resize_Handler(New_Size); end if; end Resize_Handler; -- Mouse event handler: function Mouse_Handler(This : in Window_Record; Mouse_Event : in Events.Mouse_Event_Record) return Boolean is begin return true; end Mouse_Handler; -- Keyboard event handler: function Keyboard_Handler(This : in Window_Record; Keyboard_Event : in Events.Keyboard_Event_Record) return Boolean is begin return true; end Keyboard_Handler; -- Window closing handler: function Window_Closing_Handler(This : in Window_Record) return Boolean is begin return true; end Window_Closing_Handler; -- Window closing message handler: -- Finds a window by its ID: function Find_Window_By_ID(ID : in Window_ID_Type) return Window is use Window_Lists; Window_Cursor : Cursor := Window_List.First; begin while Has_Element(Window_Cursor) loop if Element(Window_Cursor).Window_ID = ID then return Element(Window_Cursor); end if; Window_Cursor := Next(Window_Cursor); end loop; return null; end Find_Window_By_ID; -- Gets the backend specific data pointer from a window by its ID: function Get_Backend_Data_For_Window_By_ID(ID : in Window_ID_Type) return Backend_Data_Ptr is Target : constant Window := Find_Window_By_ID(ID); begin return Target.Backend_Data; end Get_Backend_Data_For_Window_By_ID; -- Posts an expose event to a window: procedure Post_Expose(ID : in Window_ID_Type) is use Cupcake.Events; Target : constant Window := Find_Window_By_ID(ID); begin if Debug_Mode then Ada.Text_IO.Put_Line("Expose event received for window" & Window_ID_Type'Image(ID)); end if; if Target = null then Ada.Text_IO.Put_Line("Invalid window ID" & Window_ID_Type'Image(ID)); else Target.Expose_Handler(Target.Graphics_Context); end if; end Post_Expose; -- Posts a resize event to a window: procedure Post_Resize(ID : in Window_ID_Type; Width, Height : in Natural) is Target : constant Window := Find_Window_By_ID(ID); begin if Debug_Mode then Ada.Text_IO.Put_Line("Resize event received for window " & Window_ID_Type'Image(ID) & " with width " & Natural'Image(Width) & " and height " & Natural'Image(Height)); end if; if Target = null then Ada.Text_IO.Put_Line("Invalid window ID" & Window_ID_Type'Image(ID)); else Target.Resize_Handler((Width, Height)); end if; end Post_Resize; -- Posts a window close event to a window: function Post_Window_Close(ID : in Window_ID_Type) return Integer is use Cupcake.Events; Target : constant Window := Find_Window_By_ID(ID); Target_Cursor : Window_Lists.Cursor := Window_List.Find(Target); Closing : Boolean := false; begin if Debug_Mode then Ada.Text_IO.Put_Line("Window close event received for window" & Window_ID_Type'Image(ID)); end if; if Target = null or not Window_Lists.Has_Element(Target_Cursor) then Ada.Text_IO.Put_Line("Invalid window ID or not visible window: " & Window_ID_Type'Image(ID)); return 0; end if; Closing := Target.Window_Closing_Handler; if Closing then Window_List.Delete(Target_Cursor); return 1; else return 0; end if; end Post_Window_Close; -- Gets the number of windows remaining: function Get_Num_Windows_Remaining return Natural is begin return Natural(Window_List.Length); end Get_Num_Windows_Remaining; end Cupcake.Windows;
Revert "Removed an incorrect comment" due to collision with new backend code
Revert "Removed an incorrect comment" due to collision with new backend code This reverts commit 03a3feb87e092822c091fd67feefb1b22f3bca07.
Ada
mit
skordal/cupcake,skordal/cupcake,skordal/cupcake
640296372ec6aca9f8a29091021ce3678458cb3d
src/wiki-render-html.adb
src/wiki-render-html.adb
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is package ACC renames Ada.Characters.Conversions; -- ------------------------------ -- Set the output stream. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Render the node instance from the document. -- ------------------------------ overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Render_Header (Header => Node.Header, Level => Node.Level); when Wiki.Nodes.N_LINE_BREAK => Engine.Output.Start_Element ("br"); Engine.Output.End_Element ("br"); when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Add_Blockquote (0); Engine.Output.Start_Element ("hr"); Engine.Output.End_Element ("hr"); when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Doc, Node.Preformatted, ""); when Wiki.Nodes.N_INDENT => -- Engine.Indent_Level := Node.Level; null; when Wiki.Nodes.N_TEXT => Engine.Add_Text (Text => Node.Text, Format => Node.Format); when Wiki.Nodes.N_QUOTE => Engine.Render_Quote (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_LINK => Engine.Render_Link (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_BLOCKQUOTE => Engine.Add_Blockquote (Node.Level); when Wiki.Nodes.N_TAG_START => Engine.Render_Tag (Doc, Node); end case; end Render; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start); Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes); begin if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := True; Engine.Need_Paragraph := False; end if; Engine.Output.Start_Element (Name.all); while Wiki.Attributes.Has_Element (Iter) loop Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := False; Engine.Need_Paragraph := True; end if; Engine.Output.End_Element (Name.all); end Render_Tag; -- ------------------------------ -- Render a section header in the document. -- ------------------------------ procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive) is begin Engine.Close_Paragraph; Engine.Add_Blockquote (0); case Level is when 1 => Engine.Output.Write_Wide_Element ("h1", Header); when 2 => Engine.Output.Write_Wide_Element ("h2", Header); when 3 => Engine.Output.Write_Wide_Element ("h3", Header); when 4 => Engine.Output.Write_Wide_Element ("h4", Header); when 5 => Engine.Output.Write_Wide_Element ("h5", Header); when 6 => Engine.Output.Write_Wide_Element ("h6", Header); when others => Engine.Output.Write_Wide_Element ("h3", Header); end case; end Render_Header; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Output.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Output.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Document.Has_Paragraph then Document.Output.End_Element ("p"); Document.Has_Paragraph := False; end if; if Document.Has_Item then Document.Output.End_Element ("li"); Document.Has_Item := False; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; while Document.Current_Level < Level loop if Ordered then Document.Output.Start_Element ("ol"); else Document.Output.Start_Element ("ul"); end if; Document.Current_Level := Document.Current_Level + 1; Document.List_Styles (Document.Current_Level) := Ordered; end loop; end Add_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Output.End_Element ("p"); end if; if Document.Has_Item then Document.Output.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Output.End_Element ("ol"); else Document.Output.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Output.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Output.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "href" then declare URI : Unbounded_Wide_Wide_String; Exists : Boolean; begin Engine.Links.Make_Page_Link (Value, URI, Exists); Engine.Output.Write_Wide_Attribute ("href", URI); end; elsif Value'Length = 0 then return; elsif Name = "hreflang" or Name = "title" or Name = "rel" or Name = "target" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("a"); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("a"); end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "alt" or Name = "longdesc" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("img"); Engine.Links.Make_Image_Link (Link, URI, Width, Height); Engine.Output.Write_Wide_Attribute ("src", URI); if Width > 0 then Engine.Output.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Engine.Output.Write_Attribute ("height", Natural'Image (Height)); end if; Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.End_Element ("img"); end Render_Image; -- ------------------------------ -- Render a quote. -- ------------------------------ procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Value'Length = 0 then return; elsif Name = "cite" or Name = "title" or Name = "lang" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("q"); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("q"); end Render_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (BOLD => HTML_BOLD'Access, ITALIC => HTML_ITALIC'Access, CODE => HTML_CODE'Access, SUPERSCRIPT => HTML_SUPERSCRIPT'Access, SUBSCRIPT => HTML_SUBSCRIPT'Access, STRIKEOUT => HTML_STRIKEOUT'Access, PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin Engine.Open_Paragraph; for I in Format'Range loop if Format (I) then Engine.Output.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Engine.Output.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Engine.Output.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String) is begin Engine.Close_Paragraph; if Format = "html" then Engine.Output.Write (Text); else Engine.Output.Start_Element ("pre"); Engine.Output.Write_Wide_Text (Text); Engine.Output.End_Element ("pre"); end if; end Render_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is package ACC renames Ada.Characters.Conversions; -- ------------------------------ -- Set the output stream. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Render the node instance from the document. -- ------------------------------ overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Render_Header (Header => Node.Header, Level => Node.Level); when Wiki.Nodes.N_LINE_BREAK => Engine.Output.Start_Element ("br"); Engine.Output.End_Element ("br"); when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Add_Blockquote (0); Engine.Output.Start_Element ("hr"); Engine.Output.End_Element ("hr"); when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_INDENT => -- Engine.Indent_Level := Node.Level; null; when Wiki.Nodes.N_LIST => Engine.Render_List_Item (Node.Level, False); when Wiki.Nodes.N_NUM_LIST => Engine.Render_List_Item (Node.Level, True); when Wiki.Nodes.N_TEXT => Engine.Add_Text (Text => Node.Text, Format => Node.Format); when Wiki.Nodes.N_QUOTE => Engine.Render_Quote (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_LINK => Engine.Render_Link (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_BLOCKQUOTE => Engine.Add_Blockquote (Node.Level); when Wiki.Nodes.N_TAG_START => Engine.Render_Tag (Doc, Node); end case; end Render; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start); Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes); begin if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := True; Engine.Need_Paragraph := False; end if; Engine.Output.Start_Element (Name.all); while Wiki.Attributes.Has_Element (Iter) loop Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := False; Engine.Need_Paragraph := True; end if; Engine.Output.End_Element (Name.all); end Render_Tag; -- ------------------------------ -- Render a section header in the document. -- ------------------------------ procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive) is begin Engine.Close_Paragraph; Engine.Add_Blockquote (0); case Level is when 1 => Engine.Output.Write_Wide_Element ("h1", Header); when 2 => Engine.Output.Write_Wide_Element ("h2", Header); when 3 => Engine.Output.Write_Wide_Element ("h3", Header); when 4 => Engine.Output.Write_Wide_Element ("h4", Header); when 5 => Engine.Output.Write_Wide_Element ("h5", Header); when 6 => Engine.Output.Write_Wide_Element ("h6", Header); when others => Engine.Output.Write_Wide_Element ("h3", Header); end case; end Render_Header; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Output.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Output.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Render 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 Render_List_Item (Engine : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Engine.Has_Paragraph then Engine.Output.End_Element ("p"); Engine.Has_Paragraph := False; end if; if Engine.Has_Item then Engine.Output.End_Element ("li"); Engine.Has_Item := False; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; while Engine.Current_Level < Level loop if Ordered then Engine.Output.Start_Element ("ol"); else Engine.Output.Start_Element ("ul"); end if; Engine.Current_Level := Engine.Current_Level + 1; Engine.List_Styles (Engine.Current_Level) := Ordered; end loop; end Render_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Output.End_Element ("p"); end if; if Document.Has_Item then Document.Output.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Output.End_Element ("ol"); else Document.Output.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Output.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Output.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "href" then declare URI : Unbounded_Wide_Wide_String; Exists : Boolean; begin Engine.Links.Make_Page_Link (Value, URI, Exists); Engine.Output.Write_Wide_Attribute ("href", URI); end; elsif Value'Length = 0 then return; elsif Name = "lang" or Name = "title" or Name = "rel" or Name = "target" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("a"); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("a"); end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "alt" or Name = "longdesc" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("img"); Engine.Links.Make_Image_Link (Link, URI, Width, Height); Engine.Output.Write_Wide_Attribute ("src", URI); if Width > 0 then Engine.Output.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Engine.Output.Write_Attribute ("height", Natural'Image (Height)); end if; Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.End_Element ("img"); end Render_Image; -- ------------------------------ -- Render a quote. -- ------------------------------ procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Value'Length = 0 then return; elsif Name = "cite" or Name = "title" or Name = "lang" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("q"); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("q"); end Render_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (BOLD => HTML_BOLD'Access, ITALIC => HTML_ITALIC'Access, CODE => HTML_CODE'Access, SUPERSCRIPT => HTML_SUPERSCRIPT'Access, SUBSCRIPT => HTML_SUBSCRIPT'Access, STRIKEOUT => HTML_STRIKEOUT'Access, PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin Engine.Open_Paragraph; for I in Format'Range loop if Format (I) then Engine.Output.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Engine.Output.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Engine.Output.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin Engine.Close_Paragraph; if Format = "html" then Engine.Output.Write (Text); else Engine.Output.Start_Element ("pre"); Engine.Output.Write_Wide_Text (Text); Engine.Output.End_Element ("pre"); end if; end Render_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
Handle the N_LIST and N_NUM_LIST nodes
Handle the N_LIST and N_NUM_LIST nodes
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
8810d49103b25f800abc5fbc3c409f3292d5b5bd
awa/plugins/awa-storages/src/awa-storages-beans.ads
awa/plugins/awa-storages/src/awa-storages-beans.ads
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Storages.Models; with AWA.Storages.Modules; with ASF.Parts; with Util.Beans.Objects; with Util.Beans.Basic; package AWA.Storages.Beans is FOLDER_ID_PARAMETER : constant String := "folderId"; -- ------------------------------ -- Upload Bean -- ------------------------------ -- The <b>Upload_Bean</b> allows to upload a file in the storage space. type Upload_Bean is new AWA.Storages.Models.Storage_Ref and Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; end record; type Upload_Bean_Access is access all Upload_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Save the uploaded file in the storage service. -- @method procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class); -- Upload the file. -- @method procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the file. -- @method procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- ------------------------------ -- Folder Bean -- ------------------------------ -- The <b>Folder_Bean</b> allows to create or update the folder name. type Folder_Bean is new AWA.Storages.Models.Storage_Folder_Ref and Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; end record; type Folder_Bean_Access is access all Folder_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the folder. procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Init_Flag is (INIT_FOLDER, INIT_FOLDER_LIST, INIT_FILE_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Storage List Bean -- ------------------------------ -- This bean represents a list of storage files for a given folder. type Storage_List_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; -- Current folder. Folder : aliased Folder_Bean; Folder_Bean : Folder_Bean_Access; -- List of folders. Folder_List : aliased AWA.Storages.Models.Folder_Info_List_Bean; Folder_List_Bean : AWA.Storages.Models.Folder_Info_List_Bean_Access; -- List of files. Files_List : aliased AWA.Storages.Models.Storage_Info_List_Bean; Files_List_Bean : AWA.Storages.Models.Storage_Info_List_Bean_Access; Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Storage_List_Bean_Access is access all Storage_List_Bean'Class; -- Load the folder instance. procedure Load_Folder (Storage : in Storage_List_Bean); -- Load the list of folders. procedure Load_Folders (Storage : in Storage_List_Bean); -- Load the list of files associated with the current folder. procedure Load_Files (Storage : in Storage_List_Bean); overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create the Folder_List_Bean bean instance. function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Storage_List_Bean bean instance. function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Storages.Models; with AWA.Storages.Modules; with ASF.Parts; with ADO; with Util.Beans.Objects; with Util.Beans.Basic; package AWA.Storages.Beans is FOLDER_ID_PARAMETER : constant String := "folderId"; -- ------------------------------ -- Upload Bean -- ------------------------------ -- The <b>Upload_Bean</b> allows to upload a file in the storage space. type Upload_Bean is new AWA.Storages.Models.Storage_Ref and Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; Folder_Id : ADO.Identifier; end record; type Upload_Bean_Access is access all Upload_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Save the uploaded file in the storage service. -- @method procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class); -- Upload the file. -- @method procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the file. -- @method procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- ------------------------------ -- Folder Bean -- ------------------------------ -- The <b>Folder_Bean</b> allows to create or update the folder name. type Folder_Bean is new AWA.Storages.Models.Storage_Folder_Ref and Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; end record; type Folder_Bean_Access is access all Folder_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the folder. procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Init_Flag is (INIT_FOLDER, INIT_FOLDER_LIST, INIT_FILE_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Storage List Bean -- ------------------------------ -- This bean represents a list of storage files for a given folder. type Storage_List_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; -- Current folder. Folder : aliased Folder_Bean; Folder_Bean : Folder_Bean_Access; -- List of folders. Folder_List : aliased AWA.Storages.Models.Folder_Info_List_Bean; Folder_List_Bean : AWA.Storages.Models.Folder_Info_List_Bean_Access; -- List of files. Files_List : aliased AWA.Storages.Models.Storage_Info_List_Bean; Files_List_Bean : AWA.Storages.Models.Storage_Info_List_Bean_Access; Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Storage_List_Bean_Access is access all Storage_List_Bean'Class; -- Load the folder instance. procedure Load_Folder (Storage : in Storage_List_Bean); -- Load the list of folders. procedure Load_Folders (Storage : in Storage_List_Bean); -- Load the list of files associated with the current folder. procedure Load_Files (Storage : in Storage_List_Bean); overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create the Folder_List_Bean bean instance. function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Storage_List_Bean bean instance. function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Storages.Beans;
Add Folder_Id to the Upload_Bean type
Add Folder_Id to the Upload_Bean type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8fce1669c7237aa80a0a60ed094e7bdce072c2de
mat/src/gtk/mat-targets-gtkmat.adb
mat/src/gtk/mat-targets-gtkmat.adb
----------------------------------------------------------------------- -- mat-targets-gtkmat - Gtk target management -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Glib.Error; with Glib.Object; with Gtk.Main; with Gtk.Label; with MAT.Callbacks; with MAT.Consoles.Text; package body MAT.Targets.Gtkmat is -- ------------------------------ -- Initialize the target instance. -- ------------------------------ overriding procedure Initialize (Target : in out Target_Type) is begin Target.Options.Interactive := False; Target.Options.Graphical := True; Target.Console := new MAT.Consoles.Text.Console_Type; end Initialize; -- ------------------------------ -- Initialize the widgets and create the Gtk gui. -- ------------------------------ procedure Initialize_Widget (Target : in out Target_Type; Widget : out Gtk.Widget.Gtk_Widget) is Error : aliased Glib.Error.GError; Result : Glib.Guint; begin if Target.Options.Graphical then Gtk.Main.Init; Gtkada.Builder.Gtk_New (Target.Builder); Result := Target.Builder.Add_From_File ("mat.glade", Error'Access); MAT.Callbacks.Initialize (Target'Unchecked_Access, Target.Builder); Target.Builder.Do_Connect; Widget := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("main")); else Widget := null; end if; end Initialize_Widget; -- ------------------------------ -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. -- ------------------------------ overriding procedure Interactive (Target : in out Target_Type) is Main : Gtk.Widget.Gtk_Widget; begin if Target.Options.Graphical then Main := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("main")); Main.Show_All; end if; if Target.Options.Interactive and Target.Options.Graphical then Target.Gui_Task.Start (Target'Unchecked_Access); end if; if Target.Options.Graphical then Gtk.Main.Main; else MAT.Targets.Target_Type (Target).Interactive; end if; end Interactive; task body Gtk_Loop is Main : Target_Type_Access; begin select accept Start (Target : in Target_Type_Access) do Main := Target; end Start; MAT.Targets.Target_Type (Main.all).Interactive; or terminate; end select; end Gtk_Loop; -- ------------------------------ -- Set the UI label with the given value. -- ------------------------------ procedure Set_Label (Target : in Target_Type; Name : in String; Value : in String) is use type Glib.Object.GObject; Object : constant Glib.Object.GObject := Target.Builder.Get_Object (Name); Label : Gtk.Label.Gtk_Label; begin if Object /= null then Label := Gtk.Label.Gtk_Label (Object); Label.Set_Label (Value); end if; end Set_Label; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ overriding procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is begin MAT.Targets.Target_Type (Target).Create_Process (Pid, Path, Process); Target.Set_Label ("process_info", "Pid:" & MAT.Types.Target_Process_Ref'Image (Pid)); end Create_Process; -- ------------------------------ -- Refresh the information about the current process. -- ------------------------------ procedure Refresh_Process (Target : in out Target_Type) is use type MAT.Events.Targets.Target_Events_Access; Counter : Integer; Stats : MAT.Memory.Targets.Memory_Stat; begin if Target.Current = null or else Target.Current.Events = null then return; end if; Counter := Target.Current.Events.Get_Event_Counter; if Counter = Target.Previous_Event_Counter then return; end if; Target.Previous_Event_Counter := Counter; Target.Set_Label ("event_info", "Events:" & Integer'Image (Counter)); Target.Current.Memory.Stat_Information (Stats); Target.Set_Label ("thread_info", "Threads:" & Natural'Image (Stats.Thread_Count)); Target.Set_Label ("mem_used_info", "Used:" & MAT.Types.Target_Size'Image (Stats.Total_Alloc)); Target.Set_Label ("mem_free_info", "Free:" & MAT.Types.Target_Size'Image (Stats.Total_Free)); end Refresh_Process; end MAT.Targets.Gtkmat;
----------------------------------------------------------------------- -- mat-targets-gtkmat - Gtk target management -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Glib.Error; with Glib.Object; with Gtk.Main; with Gtk.Label; with Gtk.Frame; with MAT.Callbacks; with MAT.Consoles.Text; with MAT.Consoles.Gtkmat; package body MAT.Targets.Gtkmat is -- ------------------------------ -- Initialize the target instance. -- ------------------------------ overriding procedure Initialize (Target : in out Target_Type) is begin Target.Options.Interactive := False; Target.Options.Graphical := True; Target.Console := new MAT.Consoles.Text.Console_Type; end Initialize; -- ------------------------------ -- Initialize the widgets and create the Gtk gui. -- ------------------------------ procedure Initialize_Widget (Target : in out Target_Type; Widget : out Gtk.Widget.Gtk_Widget) is Error : aliased Glib.Error.GError; Result : Glib.Guint; begin if Target.Options.Graphical then Gtk.Main.Init; Gtkada.Builder.Gtk_New (Target.Builder); Result := Target.Builder.Add_From_File ("mat.glade", Error'Access); MAT.Callbacks.Initialize (Target'Unchecked_Access, Target.Builder); Target.Builder.Do_Connect; Widget := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("main")); Target.Gtk_Console := new MAT.Consoles.Gtkmat.Console_Type; Target.Gtk_Console.Initialize (Gtk.Frame.Gtk_Frame (Target.Builder.Get_Object ("consoleFrame"))); Target.Console := Target.Gtk_Console.all'Access; else Widget := null; end if; end Initialize_Widget; -- ------------------------------ -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. -- ------------------------------ overriding procedure Interactive (Target : in out Target_Type) is Main : Gtk.Widget.Gtk_Widget; begin if Target.Options.Graphical then Main := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("main")); Main.Show_All; end if; if Target.Options.Interactive and Target.Options.Graphical then Target.Gui_Task.Start (Target'Unchecked_Access); end if; if Target.Options.Graphical then Gtk.Main.Main; else MAT.Targets.Target_Type (Target).Interactive; end if; end Interactive; task body Gtk_Loop is Main : Target_Type_Access; begin select accept Start (Target : in Target_Type_Access) do Main := Target; end Start; MAT.Targets.Target_Type (Main.all).Interactive; or terminate; end select; end Gtk_Loop; -- ------------------------------ -- Set the UI label with the given value. -- ------------------------------ procedure Set_Label (Target : in Target_Type; Name : in String; Value : in String) is use type Glib.Object.GObject; Object : constant Glib.Object.GObject := Target.Builder.Get_Object (Name); Label : Gtk.Label.Gtk_Label; begin if Object /= null then Label := Gtk.Label.Gtk_Label (Object); Label.Set_Label (Value); end if; end Set_Label; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ overriding procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is begin MAT.Targets.Target_Type (Target).Create_Process (Pid, Path, Process); Target.Set_Label ("process_info", "Pid:" & MAT.Types.Target_Process_Ref'Image (Pid)); end Create_Process; -- ------------------------------ -- Refresh the information about the current process. -- ------------------------------ procedure Refresh_Process (Target : in out Target_Type) is use type MAT.Events.Targets.Target_Events_Access; Counter : Integer; Stats : MAT.Memory.Targets.Memory_Stat; begin if Target.Current = null or else Target.Current.Events = null then return; end if; Counter := Target.Current.Events.Get_Event_Counter; if Counter = Target.Previous_Event_Counter then return; end if; Target.Previous_Event_Counter := Counter; Target.Set_Label ("event_info", "Events:" & Integer'Image (Counter)); Target.Current.Memory.Stat_Information (Stats); Target.Set_Label ("thread_info", "Threads:" & Natural'Image (Stats.Thread_Count)); Target.Set_Label ("mem_used_info", "Used:" & MAT.Types.Target_Size'Image (Stats.Total_Alloc)); Target.Set_Label ("mem_free_info", "Free:" & MAT.Types.Target_Size'Image (Stats.Total_Free)); end Refresh_Process; end MAT.Targets.Gtkmat;
Create the gtkmat console and use it in gui mode
Create the gtkmat console and use it in gui mode
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
bbbb25892af13026c1484e138bcddba1f8d27cef
src/util-properties.adb
src/util-properties.adb
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- with Util.Properties.Factories; with Ada.IO_Exceptions; with Ada.Strings.Unbounded.Text_IO; with Interfaces.C.Strings; with Ada.Unchecked_Deallocation; package body Util.Properties is use Ada.Text_IO; use Ada.Strings.Unbounded.Text_IO; use Interface_P; use Util.Beans.Objects; procedure Free is new Ada.Unchecked_Deallocation (Object => Interface_P.Manager'Class, Name => Interface_P.Manager_Access); type Property_Map is new Interface_P.Manager with record Props : Util.Beans.Objects.Maps.Map_Bean; end record; type Property_Map_Access is access all Property_Map; -- 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 Property_Map; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Property_Map; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. overriding function Exists (Self : in Property_Map; Name : in String) return Boolean; -- Remove the property given its name. overriding procedure Remove (Self : in out Property_Map; Name : in Value); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. overriding procedure Iterate (Self : in Property_Map; Process : access procedure (Name, Item : Value)); -- Deep copy of properties stored in 'From' to 'To'. overriding function Create_Copy (Self : in Property_Map) return Interface_P.Manager_Access; overriding function Get_Names (Self : in Property_Map; Prefix : in String) return Name_Array; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- ------------------------------ -- 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 Property_Map; Name : in String) return Util.Beans.Objects.Object is begin return From.Props.Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. -- ------------------------------ overriding procedure Set_Value (From : in out Property_Map; Name : in String; Value : in Util.Beans.Objects.Object) is begin From.Props.Set_Value (Name, Value); end Set_Value; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ overriding function Exists (Self : in Property_Map; Name : in String) return Boolean is begin return Self.Props.Contains (Name); end Exists; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ overriding procedure Remove (Self : in out Property_Map; Name : in Value) is begin null; end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. overriding procedure Iterate (Self : in Property_Map; Process : access procedure (Name, Item : Value)) is begin null; end Iterate; -- Deep copy of properties stored in 'From' to 'To'. overriding function Create_Copy (Self : in Property_Map) return Interface_P.Manager_Access is Result : Property_Map_Access := new Property_Map; begin Result.Props := Self.Props; return Result.all'Access; end Create_Copy; overriding function Get_Names (Self : in Property_Map; Prefix : in String) return Name_Array is N : Name_Array (1 .. 0); begin return N; end Get_Names; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object is begin if From.Impl = null then return Util.Beans.Objects.Null_Object; else return From.Impl.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. -- ------------------------------ overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object) is begin Check_And_Create_Impl (From); From.Impl.Set_Value (Name, Value); end Set_Value; function Exists (Self : in Manager'Class; Name : in String) return Boolean is begin -- There is not yet an implementation, no property return Self.Impl /= null and then Self.Impl.Exists (Name); end Exists; function Exists (Self : in Manager'Class; Name : in Value) return Boolean is begin -- There is not yet an implementation, no property return Self.Impl /= null and then Self.Impl.Exists (-Name); end Exists; function Get (Self : in Manager'Class; Name : in String) return Value is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return Value (To_Unbounded_String (Self.Impl.Get_Value (Name))); end Get; function Get (Self : in Manager'Class; Name : in Value) return Value is begin return Self.Get (-Name); end Get; function Get (Self : in Manager'Class; Name : in String) return String is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return To_String (Self.Impl.Get_Value (Name)); end Get; function Get (Self : in Manager'Class; Name : in Value) return String is begin if Self.Impl = null then raise NO_PROPERTY; end if; return To_String (Self.Get_Value (-Name)); end Get; function Get (Self : in Manager'Class; Name : in String; Default : in String) return String is begin if Exists (Self, Name) then return Get (Self, Name); else return Default; end if; end Get; procedure Check_And_Create_Impl (Self : in out Manager) is begin if Self.Impl = null then Self.Impl := new Property_Map; Util.Concurrent.Counters.Increment (Self.Impl.Count); elsif Util.Concurrent.Counters.Value (Self.Impl.Count) > 1 then declare Old : Interface_P.Manager_Access := Self.Impl; Is_Zero : Boolean; begin Self.Impl := Create_Copy (Self.Impl.all); Util.Concurrent.Counters.Increment (Self.Impl.Count); Util.Concurrent.Counters.Decrement (Old.Count, Is_Zero); if Is_Zero then Free (Old); end if; end; end if; end Check_And_Create_Impl; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in String; Item : in String) is begin Self.Set_Value (Name, To_Object (Item)); end Set; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value) is begin Self.Set_Value (Name, To_Object (Item)); end Set; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value) is begin Self.Set_Value (-Name, To_Object (Item)); end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in String) is begin if Self.Impl = null then raise NO_PROPERTY with "No property '" & Name & "'"; end if; Check_And_Create_Impl (Self); Remove (Self.Impl.all, +Name); end Remove; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in Value) is begin Self.Remove (-Name); end Remove; -- ------------------------------ -- Iterate over the properties and execute the given procedure passing the -- property name and its value. -- ------------------------------ procedure Iterate (Self : in Manager'Class; Process : access procedure (Name, Item : Value)) is begin if Self.Impl /= null then Self.Impl.Iterate (Process); end if; end Iterate; -- ------------------------------ -- Return the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with -- the prefix are returned. -- ------------------------------ function Get_Names (Self : in Manager; Prefix : in String := "") return Name_Array is begin if Self.Impl = null then declare Empty : Name_Array (1 .. 0); begin return Empty; end; else return Get_Names (Self.Impl.all, Prefix); end if; end Get_Names; procedure Adjust (Object : in out Manager) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Count); end if; end Adjust; procedure Finalize (Object : in out Manager) is Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Count, Is_Zero); if Is_Zero then Free (Object.Impl); end if; end if; end Finalize; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is pragma Unreferenced (Strip); Line : Unbounded_String; Pos : Natural; Len : Natural; begin while not End_Of_File (File) loop Line := Get_Line (File); Len := Length (Line); if Len /= 0 and then Element (Line, 1) /= '#' then Pos := Index (Line, "="); if Pos > 0 and then Prefix'Length > 0 and then Index (Line, Prefix) = 1 then Name := Unbounded_Slice (Line, Prefix'Length + 1, Pos - 1); Value := Tail (Line, Len - Pos); return; elsif Pos > 0 and Prefix'Length = 0 then Name := Head (Line, Pos - 1); Value := Tail (Line, Len - Pos); return; end if; end if; end loop; Name := Null_Unbounded_String; Value := Null_Unbounded_String; end Load_Property; procedure Load_Properties (Self : in out Manager'Class; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is Name, Value : Unbounded_String; begin loop Load_Property (Name, Value, File, Prefix, Strip); exit when Name = Null_Unbounded_String; Set (Self, Name, Value); end loop; exception when End_Error => return; end Load_Properties; procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False) is F : File_Type; begin Open (F, In_File, Path); Load_Properties (Self, F, Prefix, Strip); Close (F); end Load_Properties; -- ------------------------------ -- Save the properties in the given file path. -- ------------------------------ procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := "") is procedure Save_Property (Name, Item : in Value); Tmp : constant String := Path & ".tmp"; F : File_Type; procedure Save_Property (Name, Item : in Value) is begin Put (F, Name); Put (F, "="); Put (F, Item); New_Line (F); end Save_Property; -- Rename a file (the Ada.Directories.Rename does not allow to use the Unix atomic file rename!) function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr; Newpath : in Interfaces.C.Strings.chars_ptr) return Integer; pragma Import (C, Sys_Rename, "rename"); Old_Path : Interfaces.C.Strings.chars_ptr; New_Path : Interfaces.C.Strings.chars_ptr; Result : Integer; begin Create (File => F, Name => Tmp); Self.Iterate (Save_Property'Access); Close (File => F); -- Do a system atomic rename of old file in the new file. -- Ada.Directories.Rename does not allow this. Old_Path := Interfaces.C.Strings.New_String (Tmp); New_Path := Interfaces.C.Strings.New_String (Path); Result := Sys_Rename (Old_Path, New_Path); Interfaces.C.Strings.Free (Old_Path); Interfaces.C.Strings.Free (New_Path); if Result /= 0 then raise Ada.IO_Exceptions.Use_Error with "Cannot rename file"; end if; end Save_Properties; -- ------------------------------ -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- ------------------------------ procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False) is Names : constant Name_Array := From.Get_Names; begin for I in Names'Range loop declare Name : Unbounded_String renames Names (I); begin if Prefix'Length = 0 or else Index (Name, Prefix) = 1 then if Strip and Prefix'Length > 0 then declare S : constant String := Slice (Name, Prefix'Length + 1, Length (Name)); begin Self.Set (+(S), From.Get (Name)); end; else Self.Set (Name, From.Get (Name)); end if; end if; end; end loop; end Copy; end Util.Properties;
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- with Util.Properties.Factories; with Ada.IO_Exceptions; with Ada.Strings.Fixed; with Ada.Strings.Unbounded.Text_IO; with Interfaces.C.Strings; with Ada.Unchecked_Deallocation; package body Util.Properties is use Ada.Text_IO; use Ada.Strings.Unbounded.Text_IO; use Interface_P; use Util.Beans.Objects; procedure Free is new Ada.Unchecked_Deallocation (Object => Interface_P.Manager'Class, Name => Interface_P.Manager_Access); type Property_Map is new Interface_P.Manager with record Props : Util.Beans.Objects.Maps.Map_Bean; end record; type Property_Map_Access is access all Property_Map; -- 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 Property_Map; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Property_Map; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. overriding function Exists (Self : in Property_Map; Name : in String) return Boolean; -- Remove the property given its name. overriding procedure Remove (Self : in out Property_Map; Name : in String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. overriding procedure Iterate (Self : in Property_Map; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)); -- Deep copy of properties stored in 'From' to 'To'. overriding function Create_Copy (Self : in Property_Map) return Interface_P.Manager_Access; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- ------------------------------ -- 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 Property_Map; Name : in String) return Util.Beans.Objects.Object is begin return From.Props.Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. -- ------------------------------ overriding procedure Set_Value (From : in out Property_Map; Name : in String; Value : in Util.Beans.Objects.Object) is begin From.Props.Set_Value (Name, Value); end Set_Value; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ overriding function Exists (Self : in Property_Map; Name : in String) return Boolean is begin return Self.Props.Contains (Name); end Exists; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ overriding procedure Remove (Self : in out Property_Map; Name : in String) is begin Self.Props.Delete (Name); end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. overriding procedure Iterate (Self : in Property_Map; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)) is Iter : Util.Beans.Objects.Maps.Cursor := Self.Props.First; begin while Util.Beans.Objects.Maps.Has_Element (Iter) loop Util.Beans.Objects.Maps.Query_Element (Iter, Process); Util.Beans.Objects.Maps.Next (Iter); end loop; end Iterate; -- Deep copy of properties stored in 'From' to 'To'. overriding function Create_Copy (Self : in Property_Map) return Interface_P.Manager_Access is Result : Property_Map_Access := new Property_Map; begin Result.Props := Self.Props; return Result.all'Access; end Create_Copy; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object is begin if From.Impl = null then return Util.Beans.Objects.Null_Object; else return From.Impl.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. -- ------------------------------ overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object) is begin Check_And_Create_Impl (From); From.Impl.Set_Value (Name, Value); end Set_Value; function Exists (Self : in Manager'Class; Name : in String) return Boolean is begin -- There is not yet an implementation, no property return Self.Impl /= null and then Self.Impl.Exists (Name); end Exists; function Exists (Self : in Manager'Class; Name : in Value) return Boolean is begin -- There is not yet an implementation, no property return Self.Impl /= null and then Self.Impl.Exists (-Name); end Exists; function Get (Self : in Manager'Class; Name : in String) return Value is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return Value (To_Unbounded_String (Self.Impl.Get_Value (Name))); end Get; function Get (Self : in Manager'Class; Name : in Value) return Value is begin return Self.Get (-Name); end Get; function Get (Self : in Manager'Class; Name : in String) return String is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return To_String (Self.Impl.Get_Value (Name)); end Get; function Get (Self : in Manager'Class; Name : in Value) return String is begin if Self.Impl = null then raise NO_PROPERTY; end if; return To_String (Self.Get_Value (-Name)); end Get; function Get (Self : in Manager'Class; Name : in String; Default : in String) return String is begin if Exists (Self, Name) then return Get (Self, Name); else return Default; end if; end Get; procedure Check_And_Create_Impl (Self : in out Manager) is begin if Self.Impl = null then Self.Impl := new Property_Map; Util.Concurrent.Counters.Increment (Self.Impl.Count); elsif Util.Concurrent.Counters.Value (Self.Impl.Count) > 1 then declare Old : Interface_P.Manager_Access := Self.Impl; Is_Zero : Boolean; begin Self.Impl := Create_Copy (Self.Impl.all); Util.Concurrent.Counters.Increment (Self.Impl.Count); Util.Concurrent.Counters.Decrement (Old.Count, Is_Zero); if Is_Zero then Free (Old); end if; end; end if; end Check_And_Create_Impl; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in String; Item : in String) is begin Self.Set_Value (Name, To_Object (Item)); end Set; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value) is begin Self.Set_Value (Name, To_Object (Item)); end Set; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value) is begin Self.Set_Value (-Name, To_Object (Item)); end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in String) is begin if Self.Impl = null then raise NO_PROPERTY with "No property '" & Name & "'"; end if; Check_And_Create_Impl (Self); Remove (Self.Impl.all, Name); end Remove; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in Value) is begin Self.Remove (-Name); end Remove; -- ------------------------------ -- Iterate over the properties and execute the given procedure passing the -- property name and its value. -- ------------------------------ procedure Iterate (Self : in Manager'Class; Process : access procedure (Name, Item : Value)) is begin if Self.Impl /= null then null; -- Self.Impl.Iterate (Process); end if; end Iterate; -- ------------------------------ -- Return the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with -- the prefix are returned. -- ------------------------------ function Get_Names (Self : in Manager; Prefix : in String := "") return Name_Array is Empty : Name_Array (1 .. 0); begin return Empty; end Get_Names; -- ------------------------------ -- Collect the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with the prefix are -- returned. -- ------------------------------ procedure Get_Names (Self : in Manager; Into : in out Util.Strings.Vectors.Vector; Prefix : in String := "") is procedure Process (Name : in String; Item : in Util.Beans.Objects.Object) is begin if Prefix'Length = 0 or else Ada.Strings.Fixed.Index (NAme, Prefix) = 1 then Into.Append (Name); end if; end Process; begin if Self.Impl /= null then Self.Impl.Iterate (Process'Access); end if; end Get_Names; procedure Adjust (Object : in out Manager) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Count); end if; end Adjust; procedure Finalize (Object : in out Manager) is Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Count, Is_Zero); if Is_Zero then Free (Object.Impl); end if; end if; end Finalize; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is pragma Unreferenced (Strip); Line : Unbounded_String; Pos : Natural; Len : Natural; begin while not End_Of_File (File) loop Line := Get_Line (File); Len := Length (Line); if Len /= 0 and then Element (Line, 1) /= '#' then Pos := Index (Line, "="); if Pos > 0 and then Prefix'Length > 0 and then Index (Line, Prefix) = 1 then Name := Unbounded_Slice (Line, Prefix'Length + 1, Pos - 1); Value := Tail (Line, Len - Pos); return; elsif Pos > 0 and Prefix'Length = 0 then Name := Head (Line, Pos - 1); Value := Tail (Line, Len - Pos); return; end if; end if; end loop; Name := Null_Unbounded_String; Value := Null_Unbounded_String; end Load_Property; procedure Load_Properties (Self : in out Manager'Class; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is Name, Value : Unbounded_String; begin loop Load_Property (Name, Value, File, Prefix, Strip); exit when Name = Null_Unbounded_String; Set (Self, Name, Value); end loop; exception when End_Error => return; end Load_Properties; procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False) is F : File_Type; begin Open (F, In_File, Path); Load_Properties (Self, F, Prefix, Strip); Close (F); end Load_Properties; -- ------------------------------ -- Save the properties in the given file path. -- ------------------------------ procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := "") is procedure Save_Property (Name, Item : in Value); Tmp : constant String := Path & ".tmp"; F : File_Type; procedure Save_Property (Name, Item : in Value) is begin Put (F, Name); Put (F, "="); Put (F, Item); New_Line (F); end Save_Property; -- Rename a file (the Ada.Directories.Rename does not allow to use the Unix atomic file rename!) function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr; Newpath : in Interfaces.C.Strings.chars_ptr) return Integer; pragma Import (C, Sys_Rename, "rename"); Old_Path : Interfaces.C.Strings.chars_ptr; New_Path : Interfaces.C.Strings.chars_ptr; Result : Integer; begin Create (File => F, Name => Tmp); Self.Iterate (Save_Property'Access); Close (File => F); -- Do a system atomic rename of old file in the new file. -- Ada.Directories.Rename does not allow this. Old_Path := Interfaces.C.Strings.New_String (Tmp); New_Path := Interfaces.C.Strings.New_String (Path); Result := Sys_Rename (Old_Path, New_Path); Interfaces.C.Strings.Free (Old_Path); Interfaces.C.Strings.Free (New_Path); if Result /= 0 then raise Ada.IO_Exceptions.Use_Error with "Cannot rename file"; end if; end Save_Properties; -- ------------------------------ -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- ------------------------------ procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False) is Names : Util.Strings.Vectors.Vector; begin From.Get_Names (Names, Prefix); for Name of Names loop if Strip and Prefix'Length > 0 then Self.Set_Value (Name (Name'First + Prefix'Length .. Name'Last), From.Get_Value (Name)); else Self.Set_Value (Name, From.Get_Value (Name)); end if; end loop; end Copy; end Util.Properties;
Refactor the Properties implementation (step 3): - Implement the Get_Names procedure to collect the property names by using the Iterate procedure - Update the Copy procedure
Refactor the Properties implementation (step 3): - Implement the Get_Names procedure to collect the property names by using the Iterate procedure - Update the Copy procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
99cd089781dc355cf23e15cf210f5c1f688300fc
src/mysql/ado-drivers-connections-mysql.adb
src/mysql/ado-drivers-connections-mysql.adb
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Identification; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Mysql; with ADO.Schemas.Mysql; with ADO.C; with Mysql.Lib; use Mysql.Lib; package body ADO.Drivers.Connections.Mysql is use ADO.Statements.Mysql; use Util.Log; use Interfaces.C; pragma Linker_Options (MYSQL_LIB_NAME); Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql"); Driver_Name : aliased constant String := "mysql"; Driver : aliased Mysql_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create query statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create query statement {0}: connection is closed", Query); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create delete statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create insert statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create update statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Autocommit then Database.Execute ("set autocommit=0"); Database.Autocommit := False; end if; Database.Execute ("start transaction;"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is Result : char; begin Result := mysql_commit (Database.Server); if Result /= nul then raise DB_Error with "Cannot commit transaction"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is Result : char; begin Result := mysql_rollback (Database.Server); if Result /= nul then raise DB_Error with "Cannot rollback transaction"; end if; end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Mysql.Load_Schema (Database, Schema); end Load_Schema; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = null then Log.Error ("Database connection is not open"); raise Connection_Error with "Database connection is closed"; end if; Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", int'Image (Result)); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin if Database.Server /= null then Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident); mysql_close (Database.Server); Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the mysql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- mysql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : out ADO.Drivers.Connections.Database_Connection_Access) is Host : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server); Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database); Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user")); Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password")); Socket : ADO.C.String_Ptr; Port : unsigned := unsigned (Config.Port); Flags : constant unsigned_long := 0; Connection : Mysql_Access; Socket_Path : constant String := Config.Get_Property ("socket"); Server : Mysql_Access; begin if Socket_Path /= "" then ADO.C.Set_String (Socket, Socket_Path); end if; if Port = 0 then Port := 3306; end if; Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), To_String (Config.Server), To_String (Config.Database)); Log.Debug ("user={0} password={1}", Config.Get_Property ("user"), Config.Get_Property ("password")); Connection := mysql_init (null); Server := mysql_real_connect (Connection, ADO.C.To_C (Host), ADO.C.To_C (Login), ADO.C.To_C (Password), ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags); if Server = null then declare Message : constant String := Strings.Value (Mysql_Error (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.URI), Message); mysql_close (Connection); raise Connection_Error with "Cannot connect to mysql server: " & Message; end; end if; D.Id := D.Id + 1; declare Ident : constant String := Util.Strings.Image (D.Id); Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); procedure Configure (Name, Item : in Util.Properties.Value) is Value : constant String := To_String (Item); begin if Name = "encoding" then Database.Execute ("SET NAMES " & Value); Database.Execute ("SET CHARACTER SET " & Value); Database.Execute ("SET CHARACTER_SET_SERVER = '" & Value & "'"); Database.Execute ("SET CHARACTER_SET_DATABASE = '" & Value & "'"); elsif Name /= "user" and Name /= "password" then Database.Execute ("SET " & To_String (Name) & "='" & Value & "'"); end if; end Configure; begin Database.Ident (1 .. Ident'Length) := Ident; Database.Server := Server; Database.Count := 1; Database.Name := Config.Database; -- Configure the connection by setting up the MySQL 'SET X=Y' SQL commands. -- Typical configuration includes: -- encoding=utf8 -- collation_connection=utf8_general_ci Config.Properties.Iterate (Process => Configure'Access); Result := Database.all'Access; end; end Create_Connection; -- ------------------------------ -- Initialize the Mysql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing mysql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Mysql driver. -- ------------------------------ overriding procedure Finalize (D : in out Mysql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the mysql driver"); mysql_server_end; end Finalize; end ADO.Drivers.Connections.Mysql;
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Identification; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Mysql; with ADO.Schemas.Mysql; with ADO.C; with Mysql.Lib; use Mysql.Lib; package body ADO.Drivers.Connections.Mysql is use ADO.Statements.Mysql; use Util.Log; use Interfaces.C; pragma Linker_Options (MYSQL_LIB_NAME); Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql"); Driver_Name : aliased constant String := "mysql"; Driver : aliased Mysql_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create query statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create query statement {0}: connection is closed", Query); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create delete statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create insert statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create update statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Autocommit then Database.Execute ("set autocommit=0"); Database.Autocommit := False; end if; Database.Execute ("start transaction;"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is Result : char; begin Result := mysql_commit (Database.Server); if Result /= nul then raise DB_Error with "Cannot commit transaction"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is Result : char; begin Result := mysql_rollback (Database.Server); if Result /= nul then raise DB_Error with "Cannot rollback transaction"; end if; end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Mysql.Load_Schema (Database, Schema); end Load_Schema; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = null then Log.Error ("Database connection is not open"); raise Connection_Error with "Database connection is closed"; end if; Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", int'Image (Result)); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin if Database.Server /= null then Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident); mysql_close (Database.Server); Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the mysql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- mysql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is Host : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server); Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database); Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user")); Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password")); Socket : ADO.C.String_Ptr; Port : unsigned := unsigned (Config.Port); Flags : constant unsigned_long := 0; Connection : Mysql_Access; Socket_Path : constant String := Config.Get_Property ("socket"); Server : Mysql_Access; begin if Socket_Path /= "" then ADO.C.Set_String (Socket, Socket_Path); end if; if Port = 0 then Port := 3306; end if; Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), To_String (Config.Server), To_String (Config.Database)); Log.Debug ("user={0} password={1}", Config.Get_Property ("user"), Config.Get_Property ("password")); Connection := mysql_init (null); Server := mysql_real_connect (Connection, ADO.C.To_C (Host), ADO.C.To_C (Login), ADO.C.To_C (Password), ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags); if Server = null then declare Message : constant String := Strings.Value (Mysql_Error (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.URI), Message); mysql_close (Connection); raise Connection_Error with "Cannot connect to mysql server: " & Message; end; end if; D.Id := D.Id + 1; declare Ident : constant String := Util.Strings.Image (D.Id); Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); procedure Configure (Name, Item : in Util.Properties.Value) is Value : constant String := To_String (Item); begin if Name = "encoding" then Database.Execute ("SET NAMES " & Value); Database.Execute ("SET CHARACTER SET " & Value); Database.Execute ("SET CHARACTER_SET_SERVER = '" & Value & "'"); Database.Execute ("SET CHARACTER_SET_DATABASE = '" & Value & "'"); elsif Name /= "user" and Name /= "password" then Database.Execute ("SET " & To_String (Name) & "='" & Value & "'"); end if; end Configure; begin Database.Ident (1 .. Ident'Length) := Ident; Database.Server := Server; Database.Name := Config.Database; -- Configure the connection by setting up the MySQL 'SET X=Y' SQL commands. -- Typical configuration includes: -- encoding=utf8 -- collation_connection=utf8_general_ci Config.Properties.Iterate (Process => Configure'Access); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the Mysql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing mysql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Mysql driver. -- ------------------------------ overriding procedure Finalize (D : in out Mysql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the mysql driver"); mysql_server_end; end Finalize; end ADO.Drivers.Connections.Mysql;
Update the Create_Connection procedure to return a reference counted value
Update the Create_Connection procedure to return a reference counted value
Ada
apache-2.0
stcarrez/ada-ado
28bacea6fdcc5747aacf9e4ffe5620a8de7b1b99
awa/plugins/awa-storages/src/model/awa-storages-beans-factories.adb
awa/plugins/awa-storages/src/model/awa-storages-beans-factories.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 ASF.Parts; with ASF.Parts.Upload_Method; with ASF.Events.Faces.Actions; package body AWA.Storages.Beans.Factories is package Upload_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Upload_Bean, Method => Upload, Name => "upload"); package Save_Part_Binding is new ASF.Parts.Upload_Method.Bind (Name => "save", Bean => Upload_Bean, Method => Save_Part); Upload_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Upload_Binding.Proxy'Access, 2 => Save_Part_Binding.Proxy'Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Upload_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Upload_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; package Folder_Save_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Folder_Bean, Method => Save, Name => "save"); Folder_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Folder_Save_Binding.Proxy'Access); -- ------------------------------ -- 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 return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); 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; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Folder_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Folder_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Folder_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Folder_Bean_Access := new Folder_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Folder_Bean; end AWA.Storages.Beans.Factories;
----------------------------------------------------------------------- -- 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 ASF.Parts; with ASF.Parts.Upload_Method; with ASF.Events.Faces.Actions; package body AWA.Storages.Beans.Factories is package Upload_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Upload_Bean, Method => Upload, Name => "upload"); package Delete_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Upload_Bean, Method => Delete, Name => "delete"); package Save_Part_Binding is new ASF.Parts.Upload_Method.Bind (Name => "save", Bean => Upload_Bean, Method => Save_Part); Upload_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Upload_Binding.Proxy'Access, 2 => Save_Part_Binding.Proxy'Access, 3 => Delete_Binding.Proxy'Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Upload_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Upload_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; package Folder_Save_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Folder_Bean, Method => Save, Name => "save"); Folder_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Folder_Save_Binding.Proxy'Access); -- ------------------------------ -- 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 return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); 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; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Folder_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Folder_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Folder_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Folder_Bean_Access := new Folder_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Folder_Bean; end AWA.Storages.Beans.Factories;
Define the delete action on the Ada bean
Define the delete action on the Ada bean
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ba1fd4c41594bbe9005b3f58b95934dca92a1f0d
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 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 AWA.Services.Contexts; with AWA.Blogs.Services; with AWA.Helpers.Requests; with AWA.Helpers.Selectors; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin if not From.Is_Null then return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); 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 Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id /= ADO.NO_IDENTIFIER then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin if not Bean.Post.Is_Inserted then Manager.Create_Post (Blog_Id => Bean.Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_Uri, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status, Result => Result); else Manager.Update_Post (Post_Id => Bean.Post.Get_Id, Title => Bean.Post.Get_Title, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; -- ------------------------------ -- Delete a post. -- ------------------------------ procedure Delete_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; begin Manager.Delete_Post (Post_Id => Bean.Post.Get_Id); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Delete_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); package Delete_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Delete_Post, Name => "delete"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access, 3 => Delete_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif From.Post.Is_Null then return Util.Beans.Objects.Null_Object; elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); elsif Name = POST_USERNAME_ATTR then return Util.Beans.Objects.To_Object (String '(From.Post.Get_Author.Get_Name)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR and not Util.Beans.Objects.Is_Empty (Value) then From.Load_Post (ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_STATUS_ATTR then From.Post.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value)); end if; end Set_Value; -- ------------------------------ -- Load the post. -- ------------------------------ procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Post.Module.Get_Session; begin Post.Post.Load (Session, Id); Post.Title := Post.Post.Get_Title; Post.Text := Post.Post.Get_Text; Post.URI := Post.Post.Get_Uri; -- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of -- objects does not work yet. Force loading the user here while the above -- session is still open. declare A : constant String := String '(Post.Post.Get_Author.Get_Name); pragma Unreferenced (A); begin null; end; end Load_Post; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Post_Bean_Access := new Post_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; function Create_From_Status is new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type, "blog_status_"); -- ------------------------------ -- Get a select item list which contains a list of post status. -- ------------------------------ function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Helpers; begin return Selectors.Create_Selector_Bean (Bundle => "blogs", Context => null, Create => Create_From_Status'Access).all'Access; end Create_Status_List; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Blogs.Services; with AWA.Helpers.Requests; with AWA.Helpers.Selectors; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Applications.Messages.Factory; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin if not From.Is_Null then return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); 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 Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id /= ADO.NO_IDENTIFIER then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Create or save the post. -- ------------------------------ procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin if not Bean.Is_Inserted then Manager.Create_Post (Blog_Id => Bean.Blog_Id, Title => Bean.Get_Title, URI => Bean.Get_Uri, Text => Bean.Get_Text, Status => Bean.Get_Status, Result => Result); else Manager.Update_Post (Post_Id => Bean.Get_Id, Title => Bean.Get_Title, Text => Bean.Get_Text, Status => Bean.Get_Status); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Save; -- ------------------------------ -- Delete a post. -- ------------------------------ procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; begin Manager.Delete_Post (Post_Id => Bean.Get_Id); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Delete; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Get_Id)); elsif Name = POST_USERNAME_ATTR then return Util.Beans.Objects.To_Object (String '(From.Get_Author.Get_Name)); else return AWA.Blogs.Models.Post_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR and not Util.Beans.Objects.Is_Empty (Value) then From.Load_Post (ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); elsif Name = POST_TEXT_ATTR then From.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_STATUS_ATTR then From.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value)); end if; end Set_Value; -- ------------------------------ -- Load the post. -- ------------------------------ procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Post.Module.Get_Session; begin Post.Load (Session, Id); -- Post.Title := Post.Post.Get_Title; -- Post.Text := Post.Post.Get_Text; -- Post.URI := Post.Post.Get_Uri; -- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of -- objects does not work yet. Force loading the user here while the above -- session is still open. declare A : constant String := String '(Post.Get_Author.Get_Name); pragma Unreferenced (A); begin null; end; end Load_Post; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Post_Bean_Access := new Post_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; function Create_From_Status is new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type, "blog_status_"); -- ------------------------------ -- Get a select item list which contains a list of post status. -- ------------------------------ function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Helpers; begin return Selectors.Create_Selector_Bean (Bundle => "blogs", Context => null, Create => Create_From_Status'Access).all'Access; end Create_Status_List; end AWA.Blogs.Beans;
Use the generated UML Ada beans - simplify the implementation - rename old operations according to UML model
Use the generated UML Ada beans - simplify the implementation - rename old operations according to UML model
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5f342c669e6edc428505364d2ca4569da1732ca4
src/wiki-render-text.ads
src/wiki-render-text.ads
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text 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; with Wiki.Strings; -- == Text 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.Text is -- ------------------------------ -- Wiki to Text renderer -- ------------------------------ type Text_Renderer is new Wiki.Render.Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Add a line break (<br>). procedure Add_Line_Break (Document : in out Text_Renderer); -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural); -- Render 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 Render_List_Item (Engine : in out Text_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Document : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Add an image. procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document); private -- Emit a new line. procedure New_Line (Document : in out Text_Renderer); procedure Close_Paragraph (Document : in out Text_Renderer); procedure Open_Paragraph (Document : in out Text_Renderer); type Text_Renderer is new Wiki.Render.Renderer with record Output : Streams.Output_Stream_Access := null; Format : Wiki.Format_Map := (others => False); Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Indent_Level : Natural := 0; end record; end Wiki.Render.Text;
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text 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; with Wiki.Strings; -- == Text 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.Text is -- ------------------------------ -- Wiki to Text renderer -- ------------------------------ type Text_Renderer is new Wiki.Render.Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Add a line break (<br>). procedure Add_Line_Break (Document : in out Text_Renderer); -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural); -- Render 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 Render_List_Item (Engine : in out Text_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document); private -- Emit a new line. procedure New_Line (Document : in out Text_Renderer); procedure Close_Paragraph (Document : in out Text_Renderer); procedure Open_Paragraph (Document : in out Text_Renderer); type Text_Renderer is new Wiki.Render.Renderer with record Output : Streams.Output_Stream_Access := null; Format : Wiki.Format_Map := (others => False); Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Indent_Level : Natural := 0; end record; end Wiki.Render.Text;
Rename Add_Link into Render_Link and Add_Image into Render_Image
Rename Add_Link into Render_Link and Add_Image into Render_Image
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
5a0c738a63e8def71bbd6c9644574bfe4f9dcf87
src/natools-s_expressions-interpreters.ads
src/natools-s_expressions-interpreters.ads
------------------------------------------------------------------------------ -- Copyright (c) 2013-2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.S_Expressions.Interpreters provides an implemntation of a -- -- dispatching command interpreter. The base list of a given S-expression -- -- is considered as list of command, either argumentless (atoms) or with a -- -- S-expression argument (sublist). Sublists that don't start with an atom -- -- are silently ignored and can be used as comments. -- -- -- -- Formal types represent common objets for all the command, Shared_State -- -- begin read/write while Shared_Context is read-only. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Lockable; private with Ada.Containers.Indefinite_Ordered_Maps; private with Natools.S_Expressions.Atom_Buffers; generic type Shared_State (<>) is limited private; type Shared_Context (<>) is limited private; package Natools.S_Expressions.Interpreters is pragma Preelaborate (Interpreters); Command_Not_Found : exception; type Command is interface; procedure Execute (Self : in out Command; State : in out Shared_State; Context : in Shared_Context; Name : in Atom) is null; -- Execute a single argumentless command procedure Execute (Self : in out Command; State : in out Shared_State; Context : in Shared_Context; Cmd : in out Lockable.Descriptor'Class) is null; -- Execute a single command with arguments type Interpreter is new Command with private; procedure Add_Command (Self : in out Interpreter; Name : in Atom; Cmd : in Command'Class); function Has_Command (Self : Interpreter; Name : Atom) return Boolean; function Is_Empty (Self : Interpreter) return Boolean; procedure Set_Fallback (Self : in out Interpreter; Name : in Atom); procedure Reset_Fallback (Self : in out Interpreter); not overriding procedure Execute (Self : in out Interpreter; Expression : in out Lockable.Descriptor'Class; State : in out Shared_State; Context : in Shared_Context); -- Execute an expression, raising Command_Not_Found on unknown commands not overriding procedure Execute (Self : in out Interpreter; Fallback : in out Command'Class; Expression : in out Lockable.Descriptor'Class; State : in out Shared_State; Context : in Shared_Context); -- Execute an expression with temporary fallback for unknown commands overriding procedure Execute (Self : in out Interpreter; State : in out Shared_State; Context : in Shared_Context; Name : in Atom); -- Execute a single argumentless command overriding procedure Execute (Self : in out Interpreter; State : in out Shared_State; Context : in Shared_Context; Cmd : in out Lockable.Descriptor'Class); -- Execute a single command with arguments private type Exception_Command is new Command with null record; function Less_Than (Left, Right : Atom) return Boolean; package Command_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Atom, Command'Class, Less_Than); type Interpreter is new Command with record Commands : Command_Maps.Map; Max_Length : Count := 0; Fallback_Name : Atom_Buffers.Atom_Refs.Reference; end record; end Natools.S_Expressions.Interpreters;
------------------------------------------------------------------------------ -- Copyright (c) 2013-2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.S_Expressions.Interpreters provides an implemntation of a -- -- dispatching command interpreter. The base list of a given S-expression -- -- is considered as list of command, either argumentless (atoms) or with a -- -- S-expression argument (sublist). Sublists that don't start with an atom -- -- are silently ignored and can be used as comments. -- -- -- -- Formal types represent common objets for all the command, Shared_State -- -- begin read/write while Shared_Context is read-only. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Lockable; private with Ada.Containers.Indefinite_Ordered_Maps; private with Natools.S_Expressions.Atom_Buffers; generic type Shared_State (<>) is limited private; type Shared_Context (<>) is limited private; package Natools.S_Expressions.Interpreters is pragma Preelaborate (Interpreters); Command_Not_Found : exception; type Command is interface; procedure Execute (Self : in out Command; State : in out Shared_State; Context : in Shared_Context; Name : in Atom) is null; -- Execute a single argumentless command procedure Execute (Self : in out Command; State : in out Shared_State; Context : in Shared_Context; Cmd : in out Lockable.Descriptor'Class) is null; -- Execute a single command with arguments type Null_Command is new Command with null record; Do_Nothing : Null_Command := Null_Command'(null record); type Interpreter is new Command with private; procedure Add_Command (Self : in out Interpreter; Name : in Atom; Cmd : in Command'Class); function Has_Command (Self : Interpreter; Name : Atom) return Boolean; function Is_Empty (Self : Interpreter) return Boolean; procedure Set_Fallback (Self : in out Interpreter; Name : in Atom); procedure Reset_Fallback (Self : in out Interpreter); not overriding procedure Execute (Self : in out Interpreter; Expression : in out Lockable.Descriptor'Class; State : in out Shared_State; Context : in Shared_Context); -- Execute an expression, raising Command_Not_Found on unknown commands not overriding procedure Execute (Self : in out Interpreter; Fallback : in out Command'Class; Expression : in out Lockable.Descriptor'Class; State : in out Shared_State; Context : in Shared_Context); -- Execute an expression with temporary fallback for unknown commands overriding procedure Execute (Self : in out Interpreter; State : in out Shared_State; Context : in Shared_Context; Name : in Atom); -- Execute a single argumentless command overriding procedure Execute (Self : in out Interpreter; State : in out Shared_State; Context : in Shared_Context; Cmd : in out Lockable.Descriptor'Class); -- Execute a single command with arguments private type Exception_Command is new Command with null record; function Less_Than (Left, Right : Atom) return Boolean; package Command_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Atom, Command'Class, Less_Than); type Interpreter is new Command with record Commands : Command_Maps.Map; Max_Length : Count := 0; Fallback_Name : Atom_Buffers.Atom_Refs.Reference; end record; end Natools.S_Expressions.Interpreters;
add a null command constant that does nothing
s_expressions-interpreters: add a null command constant that does nothing
Ada
isc
faelys/natools
89a26337e8785680ca6fe320521d7514b37b28d0
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- 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. ----------------------------------------------------------------------- -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- 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. ----------------------------------------------------------------------- -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Definition is function Permission return Permission_Index; pragma Inline_Always (Permission); end Definition; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); private -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; end Security.Permissions;
Rename the package Permission_ACL into Definition
Rename the package Permission_ACL into Definition
Ada
apache-2.0
stcarrez/ada-security
fd1feacc3add07d0648ee46a5bd35ae715cd2b54
mat/src/mat-events.adb
mat/src/mat-events.adb
----------------------------------------------------------------------- -- gprofiler-events - Profiler Events Description -- 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 Interfaces; with Ada.Text_IO; use Ada.Text_IO; with MAT.Types; package body MAT.Events is procedure Dump (Value : in Event_Data; Attr : in Attribute); function Hex_Image (Val : MAT.Types.Uint32; Len : Positive) return String; function Hex_Image (Val : in MAT.Types.Uint32; Len : Positive) return String is Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Len) := (others => '0'); P : MAT.Types.Uint32 := Val; N : MAT.Types.Uint32; I : Positive := Len; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; procedure Dump (Value : in Event_Data; Attr : in Attribute) is begin Put (" " & Attr.Name.all); Set_Col (30); case Value.Kind is when T_UINT8 => Put (MAT.Types.Uint8'Image (Value.U8)); when T_UINT16 => Put (MAT.Types.Uint16'Image (Value.U16)); when T_UINT32 | T_SIZE_T => Put (MAT.Types.Uint32'Image (Value.U32)); when T_POINTER => Put (Hex_Image (Value.U32, 8)); when T_UINT64 => Put (MAT.Types.Uint64'Image (Value.U64)); when T_PROBE => Put_Line ("Th " & MAT.Types.Uint32'Image (Value.Probe.Thread)); Set_Col (29); for I in 1 .. Natural (Value.Probe.Cur_Depth) loop exit when I > Value.Probe.Frame'Last; if Col > 80 - 14 then Set_Col (29); end if; Put (" {" & Hex_Image (Unsigned_32 (Value.Probe.Frame (I)), 8) & "}"); end loop; when others => null; end case; New_Line; end Dump; procedure Dump (Table : in Event_Data_Table; Def : in Event_Description) is begin Put_Line (Ada.Strings.Unbounded.To_String (Def.Name) & ":"); for I in 1 .. Def.Nb_Attributes loop Dump (Table (I), Def.Def (I)); end loop; end Dump; end MAT.Events;
----------------------------------------------------------------------- -- gprofiler-events - Profiler Events Description -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; package body MAT.Events is procedure Dump (Value : in Event_Data; Attr : in Attribute); procedure Dump (Value : in Event_Data; Attr : in Attribute) is use type Ada.Text_IO.Positive_Count; begin Ada.Text_IO.Put (" " & Attr.Name.all); Ada.Text_IO.Set_Col (30); case Value.Kind is when T_UINT8 => Ada.Text_IO.Put (MAT.Types.Uint8'Image (Value.U8)); when T_UINT16 => Ada.Text_IO.Put (MAT.Types.Uint16'Image (Value.U16)); when T_UINT32 | T_SIZE_T => Ada.Text_IO.Put (MAT.Types.Uint32'Image (Value.U32)); when T_POINTER => Ada.Text_IO.Put (MAT.Types.Hex_Image (Value.U32, 8)); when T_UINT64 => Ada.Text_IO.Put (MAT.Types.Uint64'Image (Value.U64)); when T_PROBE => Ada.Text_IO.Put_Line ("Th " & MAT.Types.Uint32'Image (Value.Probe.Thread)); Ada.Text_IO.Set_Col (29); for I in 1 .. Value.Probe.Cur_Depth loop exit when I > Value.Probe.Frame'Last; if Ada.Text_IO.Col > 80 - 14 then Ada.Text_IO.Set_Col (29); end if; Ada.Text_IO.Put (" {" & MAT.Types.Hex_Image (Unsigned_32 (Value.Probe.Frame (I)), 8) & "}"); end loop; when others => null; end case; Ada.Text_IO.New_Line; end Dump; procedure Dump (Table : in Event_Data_Table; Def : in Event_Description) is begin Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Def.Name) & ":"); for I in 1 .. Def.Nb_Attributes loop Dump (Table (I), Def.Def (I)); end loop; end Dump; end MAT.Events;
Fix compilation warnings and use MAT.Types.Hex_Image
Fix compilation warnings and use MAT.Types.Hex_Image
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
9c61c2d732c632a3ec4637140e4066702def02dd
src/base/commands/util-commands-drivers.adb
src/base/commands/util-commands-drivers.adb
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is use Ada.Strings.Unbounded; -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); function "-" (Message : in String) return String is (Translate (Message)) with Inline; -- ------------------------------ -- Get the description associated with the command. -- ------------------------------ function Get_Description (Command : in Command_Type) return String is begin return To_String (Command.Description); end Get_Description; -- ------------------------------ -- Get the name used to register the command. -- ------------------------------ function Get_Name (Command : in Command_Type) return String is begin return To_String (Command.Name); end Get_Name; -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is Config : Config_Type; begin Command_Type'Class (Command).Setup (Config, Context); Config_Parser.Usage (Name, Config); end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in out Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Compute_Size (Position : in Command_Sets.Cursor); procedure Print (Position : in Command_Sets.Cursor); Column : Ada.Text_IO.Positive_Count := 1; procedure Compute_Size (Position : in Command_Sets.Cursor) is Cmd : constant Command_Access := Command_Sets.Element (Position); Len : constant Natural := Length (Cmd.Name); begin if Natural (Column) < Len then Column := Ada.Text_IO.Positive_Count (Len); end if; end Compute_Size; procedure Print (Position : in Command_Sets.Cursor) is Cmd : constant Command_Access := Command_Sets.Element (Position); begin Put (" "); Put (To_String (Cmd.Name)); if Length (Cmd.Description) > 0 then Set_Col (Column + 7); Put (To_String (Cmd.Description)); end if; New_Line; end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args, Context); New_Line; Put ("Type '"); Put (Driver_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line (-("Available subcommands:")); Command.Driver.List.Iterate (Process => Compute_Size'Access); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error (-("Unknown command '{0}'"), Cmd_Name); raise Not_Found; else Target_Cmd.Help (Cmd_Name, Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Help_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Report the command usage. -- ------------------------------ procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin Put_Line (To_String (Driver.Desc)); New_Line; if Name'Length > 0 then declare Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Usage (Name, Context); else Put (-("Invalid command")); end if; end; else Put (-("Usage: ")); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end if; end Usage; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Command); end Add_Command; procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Description := To_Unbounded_String (Description); Add_Command (Driver, Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Handler : in Command_Handler) is Command : constant Command_Access := new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Description => To_Unbounded_String (Description), Name => To_Unbounded_String (Name), Handler => Handler); begin Driver.List.Include (Command); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Cmd : aliased Help_Command_Type; Pos : Command_Sets.Cursor; begin Cmd.Name := To_Unbounded_String (Name); Pos := Driver.List.Find (Cmd'Unchecked_Access); if Command_Sets.Has_Element (Pos) then return Command_Sets.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Execute (Cmd_Args : in Argument_List'Class); Command : constant Command_Access := Driver.Find_Command (Name); procedure Execute (Cmd_Args : in Argument_List'Class) is begin Command.Execute (Name, Cmd_Args, Context); end Execute; begin if Command /= null then declare Config : Config_Type; begin Command.Setup (Config, Context); Config_Parser.Execute (Config, Args, Execute'Access); end; else Logs.Error (-("Unkown command '{0}'"), Name); raise Not_Found; end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is pragma Unreferenced (Driver); begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in out Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Handler_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Strings.Formats; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is use Ada.Strings.Unbounded; -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); function "-" (Message : in String) return String is (Translate (Message)) with Inline; -- ------------------------------ -- Get the description associated with the command. -- ------------------------------ function Get_Description (Command : in Command_Type) return String is begin return To_String (Command.Description); end Get_Description; -- ------------------------------ -- Get the name used to register the command. -- ------------------------------ function Get_Name (Command : in Command_Type) return String is begin return To_String (Command.Name); end Get_Name; -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is Config : Config_Type; begin Command_Type'Class (Command).Setup (Config, Context); Config_Parser.Usage (Name, Config); end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in out Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Compute_Size (Position : in Command_Sets.Cursor); procedure Print (Position : in Command_Sets.Cursor); Column : Ada.Text_IO.Positive_Count := 1; procedure Compute_Size (Position : in Command_Sets.Cursor) is Cmd : constant Command_Access := Command_Sets.Element (Position); Len : constant Natural := Length (Cmd.Name); begin if Natural (Column) < Len then Column := Ada.Text_IO.Positive_Count (Len); end if; end Compute_Size; procedure Print (Position : in Command_Sets.Cursor) is Cmd : constant Command_Access := Command_Sets.Element (Position); begin Put (" "); Put (To_String (Cmd.Name)); if Length (Cmd.Description) > 0 then Set_Col (Column + 7); Put (To_String (Cmd.Description)); end if; New_Line; end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args, Context); New_Line; Put_Line (Strings.Formats.Format (-("Type '{0} help {command}' for help " & "on a specific command."), Driver_Name)); Put_Line (-("Available subcommands:")); Put (Driver_Name); Command.Driver.List.Iterate (Process => Compute_Size'Access); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error (-("Unknown command '{0}'"), Cmd_Name); raise Not_Found; else Target_Cmd.Help (Cmd_Name, Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Help_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Report the command usage. -- ------------------------------ procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin Put_Line (To_String (Driver.Desc)); New_Line; if Name'Length > 0 then declare Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Usage (Name, Context); else Put (-("Invalid command")); end if; end; else Put (-("Usage: ")); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end if; end Usage; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Command); end Add_Command; procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Description := To_Unbounded_String (Description); Add_Command (Driver, Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Handler : in Command_Handler) is Command : constant Command_Access := new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Description => To_Unbounded_String (Description), Name => To_Unbounded_String (Name), Handler => Handler); begin Driver.List.Include (Command); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Cmd : aliased Help_Command_Type; Pos : Command_Sets.Cursor; begin Cmd.Name := To_Unbounded_String (Name); Pos := Driver.List.Find (Cmd'Unchecked_Access); if Command_Sets.Has_Element (Pos) then return Command_Sets.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Execute (Cmd_Args : in Argument_List'Class); Command : constant Command_Access := Driver.Find_Command (Name); procedure Execute (Cmd_Args : in Argument_List'Class) is begin Command.Execute (Name, Cmd_Args, Context); end Execute; begin if Command /= null then declare Config : Config_Type; begin Command.Setup (Config, Context); Config_Parser.Execute (Config, Args, Execute'Access); end; else Logs.Error (-("Unknown command '{0}'"), Name); raise Not_Found; end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is pragma Unreferenced (Driver); begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in out Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Handler_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
Use the Util.Strings.Formats.Format function to format a message that is localized
Use the Util.Strings.Formats.Format function to format a message that is localized
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c10ca541318753bd93606a4008fad57045cf5884
src/asf-security-filters.adb
src/asf-security-filters.adb
----------------------------------------------------------------------- -- security-filters -- Security filter -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Log.Loggers; with ASF.Cookies; with ASF.Applications.Main; with Security.Contexts; with Security.Policies.Urls; package body ASF.Security.Filters is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Filters"); -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Auth_Filter; Context : in ASF.Servlets.Servlet_Registry'Class) is use ASF.Applications.Main; begin if Context in Application'Class then Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager); end if; end Initialize; -- ------------------------------ -- Set the permission manager that must be used to verify the permission. -- ------------------------------ procedure Set_Permission_Manager (Filter : in out Auth_Filter; Manager : in Policies.Policy_Manager_Access) is begin Filter.Manager := Manager; end Set_Permission_Manager; -- ------------------------------ -- Filter the request to make sure the user is authenticated. -- Invokes the <b>Do_Login</b> procedure if there is no user. -- If a permission manager is defined, check that the user has the permission -- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission -- is denied. -- ------------------------------ procedure Do_Filter (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain) is use Ada.Strings.Unbounded; use Policies.Urls; use type Policies.Policy_Manager_Access; Session : ASF.Sessions.Session; SID : Unbounded_String; AID : Unbounded_String; Auth : ASF.Principals.Principal_Access; pragma Unreferenced (SID); procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie); -- ------------------------------ -- Collect the AID and SID cookies. -- ------------------------------ procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is Name : constant String := ASF.Cookies.Get_Name (Cookie); begin if Name = SID_COOKIE then SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie)); elsif Name = AID_COOKIE then AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie)); end if; end Fetch_Cookie; Context : aliased Contexts.Security_Context; begin Request.Iterate_Cookies (Fetch_Cookie'Access); Session := Request.Get_Session (Create => True); -- If the session does not have a principal, try to authenticate the user with -- the auto-login cookie. Auth := Session.Get_Principal; if Auth = null then Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth); if Auth /= null then Session.Set_Principal (Auth); end if; end if; -- No principal, redirect to the login page. if Auth = null then Auth_Filter'Class (F).Do_Login (Request, Response); return; end if; -- A permission manager is installed, check that the user can display the page. if F.Manager /= null then Context.Set_Context (F.Manager, Auth.all'Access); declare URI : constant String := Request.Get_Path_Info; Perm : constant Policies.URLs.URI_Permission (URI'Length) := URI_Permission '(Len => URI'Length, URI => URI); begin if not F.Manager.Has_Permission (Context, Perm) then Log.Info ("Deny access on {0}", URI); -- Auth_Filter'Class (F).Do_Deny (Request, Response); -- return; end if; end; end if; -- Request is authorized, proceed to the next filter. ASF.Servlets.Do_Filter (Chain => Chain, Request => Request, Response => Response); end Do_Filter; -- ------------------------------ -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. -- ------------------------------ procedure Do_Login (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is begin null; end Do_Login; -- ------------------------------ -- Display the forbidden access page. This procedure is called when the user is not -- authorized to see the page. The default implementation returns the SC_FORBIDDEN error. -- ------------------------------ procedure Do_Deny (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (F, Request); begin Response.Set_Status (ASF.Responses.SC_FORBIDDEN); end Do_Deny; -- ------------------------------ -- Authenticate a user by using the auto-login cookie. This procedure is called if the -- current session does not have any principal. Based on the request and the optional -- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return -- a principal object. The principal object will be freed when the session is closed. -- If the user cannot be authenticated, the returned principal should be null. -- -- The default implementation returns a null principal. -- ------------------------------ procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access) is pragma Unreferenced (F, Request, Response, Session, Auth_Id); begin Principal := null; end Authenticate; end ASF.Security.Filters;
----------------------------------------------------------------------- -- security-filters -- Security filter -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Log.Loggers; with ASF.Cookies; with ASF.Applications.Main; with Security.Contexts; with Security.Policies.Urls; package body ASF.Security.Filters is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Filters"); -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Auth_Filter; Context : in ASF.Servlets.Servlet_Registry'Class) is use ASF.Applications.Main; begin if Context in Application'Class then Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager); end if; end Initialize; -- ------------------------------ -- Set the permission manager that must be used to verify the permission. -- ------------------------------ procedure Set_Permission_Manager (Filter : in out Auth_Filter; Manager : in Policies.Policy_Manager_Access) is begin Filter.Manager := Manager; end Set_Permission_Manager; -- ------------------------------ -- Filter the request to make sure the user is authenticated. -- Invokes the <b>Do_Login</b> procedure if there is no user. -- If a permission manager is defined, check that the user has the permission -- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission -- is denied. -- ------------------------------ procedure Do_Filter (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain) is use Ada.Strings.Unbounded; use Policies.Urls; use type Policies.Policy_Manager_Access; Session : ASF.Sessions.Session; SID : Unbounded_String; AID : Unbounded_String; Auth : ASF.Principals.Principal_Access; pragma Unreferenced (SID); procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie); -- ------------------------------ -- Collect the AID and SID cookies. -- ------------------------------ procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is Name : constant String := ASF.Cookies.Get_Name (Cookie); begin if Name = SID_COOKIE then SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie)); elsif Name = AID_COOKIE then AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie)); end if; end Fetch_Cookie; Context : aliased Contexts.Security_Context; begin Request.Iterate_Cookies (Fetch_Cookie'Access); Session := Request.Get_Session (Create => True); -- If the session does not have a principal, try to authenticate the user with -- the auto-login cookie. Auth := Session.Get_Principal; if Auth = null then Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth); if Auth /= null then Session.Set_Principal (Auth); end if; end if; -- No principal, redirect to the login page. if Auth = null then Auth_Filter'Class (F).Do_Login (Request, Response); return; end if; -- A permission manager is installed, check that the user can display the page. if F.Manager /= null then Context.Set_Context (F.Manager, Auth.all'Access); declare URI : constant String := Request.Get_Path_Info; Perm : constant Policies.URLs.URI_Permission (1, URI'Length) := URI_Permission '(1, Len => URI'Length, URI => URI); begin if not F.Manager.Has_Permission (Context, Perm) then Log.Info ("Deny access on {0}", URI); -- Auth_Filter'Class (F).Do_Deny (Request, Response); -- return; end if; end; end if; -- Request is authorized, proceed to the next filter. ASF.Servlets.Do_Filter (Chain => Chain, Request => Request, Response => Response); end Do_Filter; -- ------------------------------ -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. -- ------------------------------ procedure Do_Login (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is begin null; end Do_Login; -- ------------------------------ -- Display the forbidden access page. This procedure is called when the user is not -- authorized to see the page. The default implementation returns the SC_FORBIDDEN error. -- ------------------------------ procedure Do_Deny (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (F, Request); begin Response.Set_Status (ASF.Responses.SC_FORBIDDEN); end Do_Deny; -- ------------------------------ -- Authenticate a user by using the auto-login cookie. This procedure is called if the -- current session does not have any principal. Based on the request and the optional -- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return -- a principal object. The principal object will be freed when the session is closed. -- If the user cannot be authenticated, the returned principal should be null. -- -- The default implementation returns a null principal. -- ------------------------------ procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access) is pragma Unreferenced (F, Request, Response, Session, Auth_Id); begin Principal := null; end Authenticate; end ASF.Security.Filters;
Fix the URL_Permission
Fix the URL_Permission
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
ff078984929dab96872676066e375f81613e99dd
awa/plugins/awa-questions/src/awa-questions-beans.ads
awa/plugins/awa-questions/src/awa-questions-beans.ads
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with AWA.Questions.Modules; with AWA.Questions.Models; package AWA.Questions.Beans is type Question_Bean is new AWA.Questions.Models.Question_Bean with record Module : AWA.Questions.Modules.Question_Module_Access := null; Count : Natural := 0; end record; type Question_Bean_Access is access all Question_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Questions_Bean bean instance. function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with AWA.Questions.Modules; with AWA.Questions.Models; package AWA.Questions.Beans is type Question_Bean is new AWA.Questions.Models.Question_Bean with record Module : AWA.Questions.Modules.Question_Module_Access := null; Count : Natural := 0; end record; type Question_Bean_Access is access all Question_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the question. procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the question. procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Questions_Bean bean instance. function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Questions.Beans;
Document the bean operations
Document the bean operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8d442adbd95d84ffec98033f648c4541f444dc1d
src/babel-stores.ads
src/babel-stores.ads
----------------------------------------------------------------------- -- babel-stores -- Storage management -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Babel.Files; with Babel.Files.Buffers; with Babel.Filters; package Babel.Stores is type Store_Type is limited interface; type Store_Type_Access is access all Store_Type'Class; procedure Read (Store : in out Store_Type; Path : in String; Into : in out Babel.Files.Buffers.Buffer) is abstract; procedure Write (Store : in out Store_Type; Path : in String; Into : in Babel.Files.Buffers.Buffer) is abstract; procedure Scan (Store : in out Store_Type; Path : in String; Into : in out Babel.Files.File_Container'Class; Filter : in Babel.Filters.Filter_Type'Class) is abstract; end Babel.Stores;
----------------------------------------------------------------------- -- babel-stores -- Storage management -- 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 Babel.Files; with Babel.Files.Buffers; with Babel.Filters; with Babel.Streams; package Babel.Stores is type Store_Type is limited interface; type Store_Type_Access is access all Store_Type'Class; -- Open a file in the store to read its content with a stream. procedure Open_File (Store : in out Store_Type; Path : in String; Stream : out Babel.Streams.Stream_Access) is abstract; procedure Read (Store : in out Store_Type; Path : in String; Into : in out Babel.Files.Buffers.Buffer) is abstract; procedure Write (Store : in out Store_Type; Path : in String; Into : in Babel.Files.Buffers.Buffer) is abstract; procedure Scan (Store : in out Store_Type; Path : in String; Into : in out Babel.Files.File_Container'Class; Filter : in Babel.Filters.Filter_Type'Class) is abstract; end Babel.Stores;
Declare the Open_File procedure
Declare the Open_File procedure
Ada
apache-2.0
stcarrez/babel
2938120c45a94e997ae7cec709353f171b856ba6
src/ado-queries.ads
src/ado-queries.ads
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == Introduction == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application. -- The benefit of the framework are the following: -- -- * The SQL query result are directly mapped in Ada records, -- * It is easy to change or tune an SQL query without re-building the application, -- * The SQL query can be easily tuned for a given database -- -- The database query framework uses an XML query file: -- -- * The XML query file defines a mapping that represents the result of SQL queries, -- * The XML mapping is used by [http://code.google.com/p/ada-gen Dynamo] to generate an Ada record, -- * The XML query file also defines a set of SQL queries, each query being identified by a unique name, -- * The XML query file is read by the application to obtain the SQL query associated with a query name, -- * The application uses the `List` procedure generated by [http://code.google.com/p/ada-gen Dynamo]. -- -- == XML Query File and Mapping == -- === XML Query File === -- The XML query file uses the `query-mapping` root element. It should -- define at most one `class` mapping and several `query` definitions. -- The `class` definition should come first before any `query` definition. -- -- <query-mapping> -- <class>...</class> -- <query>...</query> -- </query-mapping> -- -- == SQL Result Mapping == -- The XML query mapping is very close to the database table mapping. -- The difference is that there is no need to specify and table name -- nor any SQL type. The XML query mapping is used to build an Ada -- record that correspond to query results. Unlike the database table mapping, -- the Ada record will not be tagged and its definition will expose all the record -- members directly. -- -- The following XML query mapping: -- -- <query-mapping> -- <class name='Samples.Model.User_Info'> -- <property name="name" type="String"> -- <comment>the user name</comment> -- </property> -- <property name="email" type="String"> -- <comment>the email address</comment> -- </property> -- </class> -- </query-mapping> -- -- will generate the following Ada record: -- -- package Samples.Model is -- type User_Info is record -- Name : Unbounded_String; -- Email : Unbounded_String; -- end record; -- end Samples.Model; -- -- The same query mapping can be used by different queries. -- -- === SQL Queries === -- The XML query file defines a list of SQL queries that the application -- can use. Each query is associated with a unique name. The application -- will use that name to identify the SQL query to execute. For each query, -- the file also describes the SQL query pattern that must be used for -- the query execution. -- -- <query name='xxx' class='Samples.Model.User_Info'> -- <sql driver='mysql'> -- select u.name, u.email from user -- </sql> -- <sql driver='sqlite'> -- ... -- </sql> -- <sql-count driver='mysql'> -- select count(*) from user u -- </sql-count> -- </query> -- -- The query contains basically two SQL patterns. The `sql` element represents -- the main SQL pattern. This is the SQL that is used by the `List` operation. -- In some cases, the result set returned by the query is limited to return only -- a maximum number of rows. This is often use in paginated lists. -- -- The `sql-count` element represents an SQL query to indicate the total number -- of elements if the SQL query was not limited. package ADO.Queries is type Query_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Info is limited private; type Query_Info_Access is access all Query_Info; type Query_Info_Ref_Access is private; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with private; type Query_Manager_Access is access all Query_Manager; Null_Query_Info_Ref : constant Query_Info_Ref_Access; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Manager : in Query_Manager'Class) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String; private -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). -- Query : Query_Info_Ref_Access; Query : Query_Index := 0; end record; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.String_Access; -- File File : Query_File_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Atomic_Ref; type Query_Table_Access is access all Query_Table; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type File_Table_Access is access all File_Table; -- -- type Query_Manager (Query_Count : Query_Index; -- File_Count : File_Index) is limited record -- Driver : ADO.Drivers.Driver_Index; -- Queries : Query_Table (1 .. Query_Count); -- Files : File_Table (1 .. File_Count); -- end record; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table_Access; Files : File_Table_Access; end record; overriding procedure Finalize (Manager : in out Query_Manager); Null_Query_Info_Ref : constant Query_Info_Ref_Access := null; end ADO.Queries;
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == Introduction == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application. -- The benefit of the framework are the following: -- -- * The SQL query result are directly mapped in Ada records, -- * It is easy to change or tune an SQL query without re-building the application, -- * The SQL query can be easily tuned for a given database -- -- The database query framework uses an XML query file: -- -- * The XML query file defines a mapping that represents the result of SQL queries, -- * The XML mapping is used by [http://code.google.com/p/ada-gen Dynamo] to generate an Ada record, -- * The XML query file also defines a set of SQL queries, each query being identified by a unique name, -- * The XML query file is read by the application to obtain the SQL query associated with a query name, -- * The application uses the `List` procedure generated by [http://code.google.com/p/ada-gen Dynamo]. -- -- == XML Query File and Mapping == -- === XML Query File === -- The XML query file uses the `query-mapping` root element. It should -- define at most one `class` mapping and several `query` definitions. -- The `class` definition should come first before any `query` definition. -- -- <query-mapping> -- <class>...</class> -- <query>...</query> -- </query-mapping> -- -- == SQL Result Mapping == -- The XML query mapping is very close to the database table mapping. -- The difference is that there is no need to specify and table name -- nor any SQL type. The XML query mapping is used to build an Ada -- record that correspond to query results. Unlike the database table mapping, -- the Ada record will not be tagged and its definition will expose all the record -- members directly. -- -- The following XML query mapping: -- -- <query-mapping> -- <class name='Samples.Model.User_Info'> -- <property name="name" type="String"> -- <comment>the user name</comment> -- </property> -- <property name="email" type="String"> -- <comment>the email address</comment> -- </property> -- </class> -- </query-mapping> -- -- will generate the following Ada record: -- -- package Samples.Model is -- type User_Info is record -- Name : Unbounded_String; -- Email : Unbounded_String; -- end record; -- end Samples.Model; -- -- The same query mapping can be used by different queries. -- -- === SQL Queries === -- The XML query file defines a list of SQL queries that the application -- can use. Each query is associated with a unique name. The application -- will use that name to identify the SQL query to execute. For each query, -- the file also describes the SQL query pattern that must be used for -- the query execution. -- -- <query name='xxx' class='Samples.Model.User_Info'> -- <sql driver='mysql'> -- select u.name, u.email from user -- </sql> -- <sql driver='sqlite'> -- ... -- </sql> -- <sql-count driver='mysql'> -- select count(*) from user u -- </sql-count> -- </query> -- -- The query contains basically two SQL patterns. The `sql` element represents -- the main SQL pattern. This is the SQL that is used by the `List` operation. -- In some cases, the result set returned by the query is limited to return only -- a maximum number of rows. This is often use in paginated lists. -- -- The `sql-count` element represents an SQL query to indicate the total number -- of elements if the SQL query was not limited. package ADO.Queries is type Query_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Info is limited private; type Query_Info_Access is access all Query_Info; type Query_Info_Ref_Access is private; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with private; type Query_Manager_Access is access all Query_Manager; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Manager : in Query_Manager'Class) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String; private -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). -- Query : Query_Info_Ref_Access; Query : Query_Index := 0; end record; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.String_Access; -- File File : Query_File_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Atomic_Ref; type Query_Table_Access is access all Query_Table; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type File_Table_Access is access all File_Table; -- -- type Query_Manager (Query_Count : Query_Index; -- File_Count : File_Index) is limited record -- Driver : ADO.Drivers.Driver_Index; -- Queries : Query_Table (1 .. Query_Count); -- Files : File_Table (1 .. File_Count); -- end record; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table_Access; Files : File_Table_Access; end record; overriding procedure Finalize (Manager : in out Query_Manager); end ADO.Queries;
Remove declaration of Null_Query_Info_Ref constant
Remove declaration of Null_Query_Info_Ref constant
Ada
apache-2.0
stcarrez/ada-ado
138ab7098804d012a928d9bbd84c83e238ad69f1
src/babel-files.ads
src/babel-files.ads
----------------------------------------------------------------------- -- bkp-files -- File and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Util.Systems.Types; with Util.Encoders.SHA1; with ADO; package Babel.Files is NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER; subtype File_Identifier is ADO.Identifier; subtype Directory_Identifier is ADO.Identifier; subtype File_Size is Long_Long_Integer; type File_Mode is mod 2**16; type Uid_Type is mod 2**16; type Gid_Type is mod 2**16; type File_Type is private; type File_Type_Array is array (Positive range <>) of File_Type; type File_Type_Array_Access is access all File_Type_Array; type Directory_Type is private; type Directory_Type_Array is array (Positive range <>) of Directory_Type; type Directory_Type_Array_Access is access all Directory_Type_Array; NO_DIRECTORY : constant Directory_Type; NO_FILE : constant File_Type; type Status_Type is mod 2**16; -- The file was modified. FILE_MODIFIED : constant Status_Type := 16#0001#; -- There was some error while processing this file. FILE_ERROR : constant Status_Type := 16#8000#; -- The SHA1 signature for the file is known and valid. FILE_HAS_SHA1 : constant Status_Type := 16#0002#; -- Allocate a File_Type entry with the given name for the directory. function Allocate (Name : in String; Dir : in Directory_Type) return File_Type; -- Allocate a Directory_Type entry with the given name for the directory. function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type; type File (Len : Positive) is record Id : File_Identifier := NO_IDENTIFIER; Size : File_Size := 0; Dir : Directory_Type := NO_DIRECTORY; Mode : File_Mode := 8#644#; User : Uid_Type := 0; Group : Gid_Type := 0; Status : Status_Type := 0; Date : Ada.Calendar.Time; SHA1 : Util.Encoders.SHA1.Hash_Array; Name : aliased String (1 .. Len); end record; -- Compare two files on their name and directory. function "<" (Left, Right : in File_Type) return Boolean; -- Return true if the file was modified and need a backup. function Is_Modified (Element : in File_Type) return Boolean; -- Return true if the file is a new file. function Is_New (Element : in File_Type) return Boolean; -- Set the file as modified. procedure Set_Modified (Element : in File_Type); -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array); -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. procedure Set_Size (Element : in File_Type; Size : in File_Size); -- Set the owner and group of the file. procedure Set_Owner (Element : in File_Type; User : in Uid_Type; Group : in Gid_Type); -- Set the file modification date. procedure Set_Date (Element : in File_Type; Date : in Util.Systems.Types.Timespec); -- Return the path for the file. function Get_Path (Element : in File_Type) return String; -- Return the path for the directory. function Get_Path (Element : in Directory_Type) return String; -- Return the SHA1 signature computed for the file. function Get_SHA1 (Element : in File_Type) return String; -- Return the file size. function Get_Size (Element : in File_Type) return File_Size; -- Return the file modification date. function Get_Date (Element : in File_Type) return Ada.Calendar.Time; -- Return the user uid. function Get_User (Element : in File_Type) return Uid_Type; -- Return the group gid. function Get_Group (Element : in File_Type) return Gid_Type; -- Return the file unix mode. function Get_Mode (Element : in File_Type) return File_Mode; type File_Container is limited interface; -- Add the file with the given name in the container. procedure Add_File (Into : in out File_Container; Element : in File_Type) is abstract; -- Add the directory with the given name in the container. procedure Add_Directory (Into : in out File_Container; Element : in Directory_Type) is abstract; -- Create a new file instance with the given name in the container. function Create (Into : in File_Container; Name : in String) return File_Type is abstract; -- Create a new directory instance with the given name in the container. function Create (Into : in File_Container; Name : in String) return Directory_Type is abstract; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. function Find (From : in File_Container; Name : in String) return File_Type is abstract; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. function Find (From : in File_Container; Name : in String) return Directory_Type is abstract; -- Set the directory object associated with the container. procedure Set_Directory (Into : in out File_Container; Directory : in Directory_Type) is abstract; -- Execute the Process procedure on each directory found in the container. procedure Each_Directory (Container : in File_Container; Process : not null access procedure (Dir : in Directory_Type)) is abstract; -- Execute the Process procedure on each file found in the container. procedure Each_File (Container : in File_Container; Process : not null access procedure (F : in File_Type)) is abstract; type Default_Container is new File_Container with private; -- Add the file with the given name in the container. overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type); -- Add the directory with the given name in the container. overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type); -- Create a new file instance with the given name in the container. overriding function Create (Into : in Default_Container; Name : in String) return File_Type; -- Create a new directory instance with the given name in the container. overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. overriding function Find (From : in Default_Container; Name : in String) return File_Type; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. overriding function Find (From : in Default_Container; Name : in String) return Directory_Type; -- Set the directory object associated with the container. overriding procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type); -- Execute the Process procedure on each directory found in the container. overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)); -- Execute the Process procedure on each file found in the container. overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)); private type File_Type is access all File; type Directory (Len : Positive) is record Id : Directory_Identifier := NO_IDENTIFIER; Parent : Directory_Type; Mode : File_Mode := 8#755#; User : Uid_Type := 0; Group : Gid_Type := 0; Files : File_Type_Array_Access; Children : Directory_Type_Array_Access; Path : Ada.Strings.Unbounded.Unbounded_String; Name : aliased String (1 .. Len); end record; type Directory_Type is access all Directory; package File_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => File_Type, "=" => "="); package Directory_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Directory_Type, "=" => "="); subtype Directory_Vector is Directory_Vectors.Vector; type Default_Container is new Babel.Files.File_Container with record Current : Directory_Type; Files : File_Vectors.Vector; Dirs : Directory_Vectors.Vector; end record; NO_DIRECTORY : constant Directory_Type := null; NO_FILE : constant File_Type := null; end Babel.Files;
----------------------------------------------------------------------- -- bkp-files -- File and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Util.Systems.Types; with Util.Encoders.SHA1; with ADO; package Babel.Files is NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER; subtype File_Identifier is ADO.Identifier; subtype Directory_Identifier is ADO.Identifier; subtype File_Size is Long_Long_Integer; type File_Mode is mod 2**16; type File_Type is private; type File_Type_Array is array (Positive range <>) of File_Type; type File_Type_Array_Access is access all File_Type_Array; type Directory_Type is private; type Directory_Type_Array is array (Positive range <>) of Directory_Type; type Directory_Type_Array_Access is access all Directory_Type_Array; NO_DIRECTORY : constant Directory_Type; NO_FILE : constant File_Type; type Status_Type is mod 2**16; -- The file was modified. FILE_MODIFIED : constant Status_Type := 16#0001#; -- There was some error while processing this file. FILE_ERROR : constant Status_Type := 16#8000#; -- The SHA1 signature for the file is known and valid. FILE_HAS_SHA1 : constant Status_Type := 16#0002#; -- Allocate a File_Type entry with the given name for the directory. function Allocate (Name : in String; Dir : in Directory_Type) return File_Type; -- Allocate a Directory_Type entry with the given name for the directory. function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type; type File (Len : Positive) is record Id : File_Identifier := NO_IDENTIFIER; Size : File_Size := 0; Dir : Directory_Type := NO_DIRECTORY; Mode : File_Mode := 8#644#; User : Uid_Type := 0; Group : Gid_Type := 0; Status : Status_Type := 0; Date : Ada.Calendar.Time; SHA1 : Util.Encoders.SHA1.Hash_Array; Name : aliased String (1 .. Len); end record; -- Compare two files on their name and directory. function "<" (Left, Right : in File_Type) return Boolean; -- Return true if the file was modified and need a backup. function Is_Modified (Element : in File_Type) return Boolean; -- Return true if the file is a new file. function Is_New (Element : in File_Type) return Boolean; -- Set the file as modified. procedure Set_Modified (Element : in File_Type); -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array); -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. procedure Set_Size (Element : in File_Type; Size : in File_Size); -- Set the owner and group of the file. procedure Set_Owner (Element : in File_Type; User : in Uid_Type; Group : in Gid_Type); -- Set the file modification date. procedure Set_Date (Element : in File_Type; Date : in Util.Systems.Types.Timespec); -- Return the path for the file. function Get_Path (Element : in File_Type) return String; -- Return the path for the directory. function Get_Path (Element : in Directory_Type) return String; -- Return the SHA1 signature computed for the file. function Get_SHA1 (Element : in File_Type) return String; -- Return the file size. function Get_Size (Element : in File_Type) return File_Size; -- Return the file modification date. function Get_Date (Element : in File_Type) return Ada.Calendar.Time; -- Return the user uid. function Get_User (Element : in File_Type) return Uid_Type; -- Return the group gid. function Get_Group (Element : in File_Type) return Gid_Type; -- Return the file unix mode. function Get_Mode (Element : in File_Type) return File_Mode; type File_Container is limited interface; -- Add the file with the given name in the container. procedure Add_File (Into : in out File_Container; Element : in File_Type) is abstract; -- Add the directory with the given name in the container. procedure Add_Directory (Into : in out File_Container; Element : in Directory_Type) is abstract; -- Create a new file instance with the given name in the container. function Create (Into : in File_Container; Name : in String) return File_Type is abstract; -- Create a new directory instance with the given name in the container. function Create (Into : in File_Container; Name : in String) return Directory_Type is abstract; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. function Find (From : in File_Container; Name : in String) return File_Type is abstract; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. function Find (From : in File_Container; Name : in String) return Directory_Type is abstract; -- Set the directory object associated with the container. procedure Set_Directory (Into : in out File_Container; Directory : in Directory_Type) is abstract; -- Execute the Process procedure on each directory found in the container. procedure Each_Directory (Container : in File_Container; Process : not null access procedure (Dir : in Directory_Type)) is abstract; -- Execute the Process procedure on each file found in the container. procedure Each_File (Container : in File_Container; Process : not null access procedure (F : in File_Type)) is abstract; type Default_Container is new File_Container with private; -- Add the file with the given name in the container. overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type); -- Add the directory with the given name in the container. overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type); -- Create a new file instance with the given name in the container. overriding function Create (Into : in Default_Container; Name : in String) return File_Type; -- Create a new directory instance with the given name in the container. overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. overriding function Find (From : in Default_Container; Name : in String) return File_Type; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. overriding function Find (From : in Default_Container; Name : in String) return Directory_Type; -- Set the directory object associated with the container. overriding procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type); -- Execute the Process procedure on each directory found in the container. overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)); -- Execute the Process procedure on each file found in the container. overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)); private type File_Type is access all File; type Directory (Len : Positive) is record Id : Directory_Identifier := NO_IDENTIFIER; Parent : Directory_Type; Mode : File_Mode := 8#755#; User : Uid_Type := 0; Group : Gid_Type := 0; Files : File_Type_Array_Access; Children : Directory_Type_Array_Access; Path : Ada.Strings.Unbounded.Unbounded_String; Name : aliased String (1 .. Len); end record; type Directory_Type is access all Directory; package File_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => File_Type, "=" => "="); package Directory_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Directory_Type, "=" => "="); subtype Directory_Vector is Directory_Vectors.Vector; type Default_Container is new Babel.Files.File_Container with record Current : Directory_Type; Files : File_Vectors.Vector; Dirs : Directory_Vectors.Vector; end record; NO_DIRECTORY : constant Directory_Type := null; NO_FILE : constant File_Type := null; end Babel.Files;
Remove Uid_Type and Gid_Type
Remove Uid_Type and Gid_Type
Ada
apache-2.0
stcarrez/babel
d894c2321adf9d0415990812fad0cc210c9b54b0
src/util-strings.ads
src/util-strings.ads
----------------------------------------------------------------------- -- Util-strings -- Various String Utility -- 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.Containers; with Ada.Containers.Indefinite_Hashed_Maps; package Util.Strings is type String_Access is access all String; -- Constant string access type Name_Access is access constant String; -- Compute the hash value of the string. function Hash (Key : Name_Access) return Ada.Containers.Hash_Type; -- Returns true if left and right strings are equivalent. function Equivalent_Keys (Left, Right : Name_Access) return Boolean; package String_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Name_Access, Element_Type => Name_Access, Hash => Hash, Equivalent_Keys => Equivalent_Keys); end Util.Strings;
----------------------------------------------------------------------- -- Util-strings -- Various String Utility -- 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.Containers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Sets; package Util.Strings is type String_Access is access all String; -- Constant string access type Name_Access is access constant String; -- Compute the hash value of the string. function Hash (Key : Name_Access) return Ada.Containers.Hash_Type; -- Returns true if left and right strings are equivalent. function Equivalent_Keys (Left, Right : Name_Access) return Boolean; package String_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Name_Access, Element_Type => Name_Access, Hash => Hash, Equivalent_Keys => Equivalent_Keys); package String_Set is new Ada.Containers.Indefinite_Hashed_Sets (Element_Type => Name_Access, Hash => Hash, Equivalent_Elements => Equivalent_Keys); end Util.Strings;
Define a package to represent and use a set of string pointers
Define a package to represent and use a set of string pointers
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
d870a50bb9fed7c3c4b3d48228bce34b7fa0b97b
src/lumen-events.adb
src/lumen-events.adb
with ada.text_io; use ada.text_io; -- Lumen.Events -- Manage input events in Lumen windows -- -- Chip Richards, NiEstu, Phoenix AZ, Spring 2010 -- This code is covered by the ISC License: -- -- Copyright © 2010, NiEstu -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- The software is provided "as is" and the author disclaims all warranties -- with regard to this software including all implied warranties of -- merchantability and fitness. In no event shall the author be liable for any -- special, direct, indirect, or consequential damages or any damages -- whatsoever resulting from loss of use, data or profits, whether in an -- action of contract, negligence or other tortious action, arising out of or -- in connection with the use or performance of this software. -- Environment with System; with Lumen.Internal; with Lumen.Window; package body Lumen.Events is --------------------------------------------------------------------------- -- Returns the number of events that are waiting in the event queue. -- Useful for more complex event loops. function Pending (Win : Window.Handle) return Natural is function X_Pending (Display : Internal.Display_Pointer) return Natural; pragma Import (C, X_Pending, "XPending"); begin -- Pending return X_Pending (Win.Display); end Pending; --------------------------------------------------------------------------- -- Retrieve the next input event from the queue and return it function Next_Event (Win : Window.Handle) return Event_Data is ------------------------------------------------------------------------ -- X event type codes X_Error : constant := 0; X_Key_Press : constant := 2; X_Key_Release : constant := 3; X_Button_Press : constant := 4; X_Button_Release : constant := 5; X_Motion_Notify : constant := 6; X_Enter_Notify : constant := 7; X_Leave_Notify : constant := 8; X_Focus_In : constant := 9; X_Focus_Out : constant := 10; X_Expose : constant := 12; X_Map_Notify : constant := 18; X_Unmap_Notify : constant := 19; X_Configure_Notify : constant := 22; X_Client_Message : constant := 33; X_First_Event : constant := X_Error; X_Last_Event : constant := X_Client_Message; -- X modifier mask and its values type Modifier_Mask is mod 2 ** Integer'Size; Shift_Mask : constant Modifier_Mask := 2#0000_0000_0000_0001#; Lock_Mask : constant Modifier_Mask := 2#0000_0000_0000_0010#; Control_Mask : constant Modifier_Mask := 2#0000_0000_0000_0100#; Mod_1_Mask : constant Modifier_Mask := 2#0000_0000_0000_1000#; Mod_2_Mask : constant Modifier_Mask := 2#0000_0000_0001_0000#; Mod_3_Mask : constant Modifier_Mask := 2#0000_0000_0010_0000#; Mod_4_Mask : constant Modifier_Mask := 2#0000_0000_0100_0000#; Mod_5_Mask : constant Modifier_Mask := 2#0000_0000_1000_0000#; Button_1_Mask : constant Modifier_Mask := 2#0000_0000_0000_0000#; Button_2_Mask : constant Modifier_Mask := 2#0000_0001_0000_0000#; Button_3_Mask : constant Modifier_Mask := 2#0000_0010_0000_0000#; Button_4_Mask : constant Modifier_Mask := 2#0000_0100_0000_0000#; Button_5_Mask : constant Modifier_Mask := 2#0001_1000_0000_0000#; type X_Event_Code is new Integer range X_First_Event .. X_Last_Event; Bytes : constant := Integer'Size / 8; Bits : constant := Integer'Size - 1; Atom_Bits : constant := Internal.Atom'Size - 1; type X_Event_Data (X_Event_Type : X_Event_Code := X_Error) is record case X_Event_Type is when X_Key_Press | X_Key_Release => Key_X : Natural; Key_Y : Natural; Key_Root_X : Natural; Key_Root_Y : Natural; Key_State : Modifier_Mask; Key_Code : Natural; when X_Button_Press | X_Button_Release => Btn_X : Natural; Btn_Y : Natural; Btn_Root_X : Natural; Btn_Root_Y : Natural; Btn_State : Modifier_Mask; Btn_Code : Natural; when X_Motion_Notify => Mov_X : Natural; Mov_Y : Natural; Mov_Root_X : Natural; Mov_Root_Y : Natural; Mov_State : Modifier_Mask; when X_Enter_Notify | X_Leave_Notify => Xng_X : Natural; Xng_Y : Natural; Xng_Root_X : Natural; Xng_Root_Y : Natural; when X_Expose => Xps_X : Natural; Xps_Y : Natural; Xps_Width : Natural; Xps_Height : Natural; Xps_Count : Natural; when X_Configure_Notify => Cfg_X : Natural; Cfg_Y : Natural; Cfg_Width : Natural; Cfg_Height : Natural; when X_Client_Message => Msg_Value : Internal.Atom; when others => Pad : Internal.Padding; end case; end record; for X_Event_Data use record X_Event_Type at 0 * Bytes range 0 .. Bits; Key_X at 16 * Bytes range 0 .. Bits; Key_Y at 17 * Bytes range 0 .. Bits; Key_Root_X at 18 * Bytes range 0 .. Bits; Key_Root_Y at 19 * Bytes range 0 .. Bits; Key_State at 20 * Bytes range 0 .. Bits; Key_Code at 21 * Bytes range 0 .. Bits; Btn_X at 16 * Bytes range 0 .. Bits; Btn_Y at 17 * Bytes range 0 .. Bits; Btn_Root_X at 18 * Bytes range 0 .. Bits; Btn_Root_Y at 19 * Bytes range 0 .. Bits; Btn_State at 20 * Bytes range 0 .. Bits; Btn_Code at 21 * Bytes range 0 .. Bits; Mov_X at 16 * Bytes range 0 .. Bits; Mov_Y at 17 * Bytes range 0 .. Bits; Mov_Root_X at 18 * Bytes range 0 .. Bits; Mov_Root_Y at 19 * Bytes range 0 .. Bits; Mov_State at 20 * Bytes range 0 .. Bits; Xng_X at 16 * Bytes range 0 .. Bits; Xng_Y at 17 * Bytes range 0 .. Bits; Xng_Root_X at 18 * Bytes range 0 .. Bits; Xng_Root_Y at 19 * Bytes range 0 .. Bits; Xps_X at 10 * Bytes range 0 .. Bits; Xps_Y at 11 * Bytes range 0 .. Bits; Xps_Width at 12 * Bytes range 0 .. Bits; Xps_Height at 13 * Bytes range 0 .. Bits; Cfg_X at 12 * Bytes range 0 .. Bits; Cfg_Y at 13 * Bytes range 0 .. Bits; Cfg_Width at 14 * Bytes range 0 .. Bits; Cfg_Height at 15 * Bytes range 0 .. Bits; Msg_Value at 14 * Bytes range 0 .. Atom_Bits; end record; ------------------------------------------------------------------------ -- Convert an X modifier mask into a Lumen modifier set function Modifier_Mask_To_Set (Mask : Modifier_Mask) return Modifier_Set is begin -- Modifier_Mask_To_Set return ( Mod_Shift => (Mask and Shift_Mask) /= 0, Mod_Lock => (Mask and Lock_Mask) /= 0, Mod_Control => (Mask and Control_Mask) /= 0, Mod_1 => (Mask and Mod_1_Mask) /= 0, Mod_2 => (Mask and Mod_2_Mask) /= 0, Mod_3 => (Mask and Mod_3_Mask) /= 0, Mod_4 => (Mask and Mod_4_Mask) /= 0, Mod_5 => (Mask and Mod_5_Mask) /= 0, Mod_Button_1 => (Mask and Button_1_Mask) /= 0, Mod_Button_2 => (Mask and Button_2_Mask) /= 0, Mod_Button_3 => (Mask and Button_3_Mask) /= 0, Mod_Button_4 => (Mask and Button_4_Mask) /= 0, Mod_Button_5 => (Mask and Button_5_Mask) /= 0 ); end Modifier_Mask_To_Set; ------------------------------------------------------------------------ X_Event : X_Event_Data; ------------------------------------------------------------------------ begin -- Next_Event -- Get the event from the X server Internal.X_Next_Event (Win.Display, X_Event'Address); -- Based on the event type, transfer and convert the event data case X_Event.X_Event_Type is when X_Key_Press => return (Which => Key_Press, Key_Data => (X => X_Event.Key_X, Y => X_Event.Key_Y, Abs_X => X_Event.Key_Root_X, Abs_Y => X_Event.Key_Root_Y, Modifiers => Modifier_Mask_To_Set (X_Event.Key_State), Key_Code => Raw_Keycode (X_Event.Key_Code))); when X_Key_Release => return (Which => Key_Release, Key_Data => (X => X_Event.Key_X, Y => X_Event.Key_Y, Abs_X => X_Event.Key_Root_X, Abs_Y => X_Event.Key_Root_Y, Modifiers => Modifier_Mask_To_Set (X_Event.Key_State), Key_Code => Raw_Keycode (X_Event.Key_Code))); when X_Button_Press => return (Which => Button_Press, Button_Data => (X => X_Event.Btn_X, Y => X_Event.Btn_Y, Abs_X => X_Event.Btn_Root_X, Abs_Y => X_Event.Btn_Root_Y, Modifiers => Modifier_Mask_To_Set (X_Event.Btn_State), Changed => Button'Val (X_Event.Btn_Code - 1))); when X_Button_Release => return (Which => Button_Release, Button_Data => (X => X_Event.Btn_X, Y => X_Event.Btn_Y, Abs_X => X_Event.Btn_Root_X, Abs_Y => X_Event.Btn_Root_Y, Modifiers => Modifier_Mask_To_Set (X_Event.Btn_State), Changed => Button'Val (X_Event.Btn_Code - 1))); when X_Motion_Notify => return (Which => Pointer_Motion, Motion_Data => (X => X_Event.Mov_X, Y => X_Event.Mov_Y, Abs_X => X_Event.Mov_Root_X, Abs_Y => X_Event.Mov_Root_Y, Modifiers => Modifier_Mask_To_Set (X_Event.Mov_State))); when X_Enter_Notify => return (Which => Enter_Window, Crossing_Data => (X => X_Event.Xng_X, Y => X_Event.Xng_Y, Abs_X => X_Event.Xng_Root_X, Abs_Y => X_Event.Xng_Root_Y)); when X_Leave_Notify => return (Which => Leave_Window, Crossing_Data => (X => X_Event.Xng_X, Y => X_Event.Xng_Y, Abs_X => X_Event.Xng_Root_X, Abs_Y => X_Event.Xng_Root_Y)); when X_Focus_In => return (Which => Focus_In); when X_Focus_Out => return (Which => Focus_Out); when X_Expose => return (Which => Exposed, Expose_Data => (X => X_Event.Xps_X, Y => X_Event.Xps_Y, Width => X_Event.Xps_Width, Height => X_Event.Xps_Height, Count => X_Event.Xps_Count)); when X_Map_Notify => -- Fake up a "whole window exposed" event return (Which => Exposed, Expose_Data => (X => 0, Y => 0, Width => Win.Width, Height => Win.Height, Count => 0)); when X_Unmap_Notify => return (Which => Hidden); when X_Configure_Notify => if X_Event.Cfg_Width /= Win.Width or X_Event.Cfg_Height /= Win.Height then Win.Width := X_Event.Cfg_Width; Win.Height := X_Event.Cfg_Height; return (Which => Resized, Resize_Data => (Width => X_Event.Cfg_Width, Height => X_Event.Cfg_Height)); else -- Fake up a "whole window exposed" event return (Which => Exposed, Expose_Data => (X => 0, Y => 0, Width => X_Event.Cfg_Width, Height => X_Event.Cfg_Height, Count => 0)); end if; when X_Client_Message => declare use type Internal.Atom; begin if X_Event.Msg_Value = Internal.Delete_Window_Atom then return (Which => Close_Window); else return (Which => Unknown_Event); end if; end; when others => return (Which => Unknown_Event); end case; end Next_Event; --------------------------------------------------------------------------- -- Simple event loop with a single callback procedure Receive_Events (Win : in Window.Handle; Call : in Event_Callback) is begin -- Receive_Events -- Get events and pass them to the callback loop Call (Next_Event (Win)); end loop; end Receive_Events; --------------------------------------------------------------------------- -- Simple event loop with multiple callbacks based on event type procedure Select_Events (Win : in Window.Handle; Calls : in Event_Callback_Table) is Event : Event_Data := Next_Event (Win); begin -- Select_Events -- Get events and pass them to the selected callback, if there is one loop if Calls (Event.Which) /= No_Callback then Calls (Event.Which) (Event); end if; end loop; end Select_Events; --------------------------------------------------------------------------- end Lumen.Events;
-- Lumen.Events -- Manage input events in Lumen windows -- -- Chip Richards, NiEstu, Phoenix AZ, Spring 2010 -- This code is covered by the ISC License: -- -- Copyright © 2010, NiEstu -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- The software is provided "as is" and the author disclaims all warranties -- with regard to this software including all implied warranties of -- merchantability and fitness. In no event shall the author be liable for any -- special, direct, indirect, or consequential damages or any damages -- whatsoever resulting from loss of use, data or profits, whether in an -- action of contract, negligence or other tortious action, arising out of or -- in connection with the use or performance of this software. -- Environment with System; with Lumen.Internal; with Lumen.Window; package body Lumen.Events is --------------------------------------------------------------------------- -- Returns the number of events that are waiting in the event queue. -- Useful for more complex event loops. function Pending (Win : Window.Handle) return Natural is function X_Pending (Display : Internal.Display_Pointer) return Natural; pragma Import (C, X_Pending, "XPending"); begin -- Pending return X_Pending (Win.Display); end Pending; --------------------------------------------------------------------------- -- Retrieve the next input event from the queue and return it function Next_Event (Win : Window.Handle) return Event_Data is ------------------------------------------------------------------------ -- X event type codes X_Error : constant := 0; X_Key_Press : constant := 2; X_Key_Release : constant := 3; X_Button_Press : constant := 4; X_Button_Release : constant := 5; X_Motion_Notify : constant := 6; X_Enter_Notify : constant := 7; X_Leave_Notify : constant := 8; X_Focus_In : constant := 9; X_Focus_Out : constant := 10; X_Expose : constant := 12; X_Map_Notify : constant := 18; X_Unmap_Notify : constant := 19; X_Configure_Notify : constant := 22; X_Client_Message : constant := 33; X_First_Event : constant := X_Error; X_Last_Event : constant := X_Client_Message; -- X modifier mask and its values type Modifier_Mask is mod 2 ** Integer'Size; Shift_Mask : constant Modifier_Mask := 2#0000_0000_0000_0001#; Lock_Mask : constant Modifier_Mask := 2#0000_0000_0000_0010#; Control_Mask : constant Modifier_Mask := 2#0000_0000_0000_0100#; Mod_1_Mask : constant Modifier_Mask := 2#0000_0000_0000_1000#; Mod_2_Mask : constant Modifier_Mask := 2#0000_0000_0001_0000#; Mod_3_Mask : constant Modifier_Mask := 2#0000_0000_0010_0000#; Mod_4_Mask : constant Modifier_Mask := 2#0000_0000_0100_0000#; Mod_5_Mask : constant Modifier_Mask := 2#0000_0000_1000_0000#; Button_1_Mask : constant Modifier_Mask := 2#0000_0000_0000_0000#; Button_2_Mask : constant Modifier_Mask := 2#0000_0001_0000_0000#; Button_3_Mask : constant Modifier_Mask := 2#0000_0010_0000_0000#; Button_4_Mask : constant Modifier_Mask := 2#0000_0100_0000_0000#; Button_5_Mask : constant Modifier_Mask := 2#0001_1000_0000_0000#; type X_Event_Code is new Integer range X_First_Event .. X_Last_Event; Bytes : constant := Integer'Size / 8; Bits : constant := Integer'Size - 1; Atom_Bits : constant := Internal.Atom'Size - 1; type X_Event_Data (X_Event_Type : X_Event_Code := X_Error) is record case X_Event_Type is when X_Key_Press | X_Key_Release => Key_X : Natural; Key_Y : Natural; Key_Root_X : Natural; Key_Root_Y : Natural; Key_State : Modifier_Mask; Key_Code : Natural; when X_Button_Press | X_Button_Release => Btn_X : Natural; Btn_Y : Natural; Btn_Root_X : Natural; Btn_Root_Y : Natural; Btn_State : Modifier_Mask; Btn_Code : Natural; when X_Motion_Notify => Mov_X : Natural; Mov_Y : Natural; Mov_Root_X : Natural; Mov_Root_Y : Natural; Mov_State : Modifier_Mask; when X_Enter_Notify | X_Leave_Notify => Xng_X : Natural; Xng_Y : Natural; Xng_Root_X : Natural; Xng_Root_Y : Natural; when X_Expose => Xps_X : Natural; Xps_Y : Natural; Xps_Width : Natural; Xps_Height : Natural; Xps_Count : Natural; when X_Configure_Notify => Cfg_X : Natural; Cfg_Y : Natural; Cfg_Width : Natural; Cfg_Height : Natural; when X_Client_Message => Msg_Value : Internal.Atom; when others => Pad : Internal.Padding; end case; end record; for X_Event_Data use record X_Event_Type at 0 * Bytes range 0 .. Bits; Key_X at 16 * Bytes range 0 .. Bits; Key_Y at 17 * Bytes range 0 .. Bits; Key_Root_X at 18 * Bytes range 0 .. Bits; Key_Root_Y at 19 * Bytes range 0 .. Bits; Key_State at 20 * Bytes range 0 .. Bits; Key_Code at 21 * Bytes range 0 .. Bits; Btn_X at 16 * Bytes range 0 .. Bits; Btn_Y at 17 * Bytes range 0 .. Bits; Btn_Root_X at 18 * Bytes range 0 .. Bits; Btn_Root_Y at 19 * Bytes range 0 .. Bits; Btn_State at 20 * Bytes range 0 .. Bits; Btn_Code at 21 * Bytes range 0 .. Bits; Mov_X at 16 * Bytes range 0 .. Bits; Mov_Y at 17 * Bytes range 0 .. Bits; Mov_Root_X at 18 * Bytes range 0 .. Bits; Mov_Root_Y at 19 * Bytes range 0 .. Bits; Mov_State at 20 * Bytes range 0 .. Bits; Xng_X at 16 * Bytes range 0 .. Bits; Xng_Y at 17 * Bytes range 0 .. Bits; Xng_Root_X at 18 * Bytes range 0 .. Bits; Xng_Root_Y at 19 * Bytes range 0 .. Bits; Xps_X at 10 * Bytes range 0 .. Bits; Xps_Y at 11 * Bytes range 0 .. Bits; Xps_Width at 12 * Bytes range 0 .. Bits; Xps_Height at 13 * Bytes range 0 .. Bits; Cfg_X at 12 * Bytes range 0 .. Bits; Cfg_Y at 13 * Bytes range 0 .. Bits; Cfg_Width at 14 * Bytes range 0 .. Bits; Cfg_Height at 15 * Bytes range 0 .. Bits; Msg_Value at 14 * Bytes range 0 .. Atom_Bits; end record; ------------------------------------------------------------------------ -- Convert an X modifier mask into a Lumen modifier set function Modifier_Mask_To_Set (Mask : Modifier_Mask) return Modifier_Set is begin -- Modifier_Mask_To_Set return ( Mod_Shift => (Mask and Shift_Mask) /= 0, Mod_Lock => (Mask and Lock_Mask) /= 0, Mod_Control => (Mask and Control_Mask) /= 0, Mod_1 => (Mask and Mod_1_Mask) /= 0, Mod_2 => (Mask and Mod_2_Mask) /= 0, Mod_3 => (Mask and Mod_3_Mask) /= 0, Mod_4 => (Mask and Mod_4_Mask) /= 0, Mod_5 => (Mask and Mod_5_Mask) /= 0, Mod_Button_1 => (Mask and Button_1_Mask) /= 0, Mod_Button_2 => (Mask and Button_2_Mask) /= 0, Mod_Button_3 => (Mask and Button_3_Mask) /= 0, Mod_Button_4 => (Mask and Button_4_Mask) /= 0, Mod_Button_5 => (Mask and Button_5_Mask) /= 0 ); end Modifier_Mask_To_Set; ------------------------------------------------------------------------ X_Event : X_Event_Data; ------------------------------------------------------------------------ begin -- Next_Event -- Get the event from the X server Internal.X_Next_Event (Win.Display, X_Event'Address); -- Based on the event type, transfer and convert the event data case X_Event.X_Event_Type is when X_Key_Press => return (Which => Key_Press, Key_Data => (X => X_Event.Key_X, Y => X_Event.Key_Y, Abs_X => X_Event.Key_Root_X, Abs_Y => X_Event.Key_Root_Y, Modifiers => Modifier_Mask_To_Set (X_Event.Key_State), Key_Code => Raw_Keycode (X_Event.Key_Code))); when X_Key_Release => return (Which => Key_Release, Key_Data => (X => X_Event.Key_X, Y => X_Event.Key_Y, Abs_X => X_Event.Key_Root_X, Abs_Y => X_Event.Key_Root_Y, Modifiers => Modifier_Mask_To_Set (X_Event.Key_State), Key_Code => Raw_Keycode (X_Event.Key_Code))); when X_Button_Press => return (Which => Button_Press, Button_Data => (X => X_Event.Btn_X, Y => X_Event.Btn_Y, Abs_X => X_Event.Btn_Root_X, Abs_Y => X_Event.Btn_Root_Y, Modifiers => Modifier_Mask_To_Set (X_Event.Btn_State), Changed => Button'Val (X_Event.Btn_Code - 1))); when X_Button_Release => return (Which => Button_Release, Button_Data => (X => X_Event.Btn_X, Y => X_Event.Btn_Y, Abs_X => X_Event.Btn_Root_X, Abs_Y => X_Event.Btn_Root_Y, Modifiers => Modifier_Mask_To_Set (X_Event.Btn_State), Changed => Button'Val (X_Event.Btn_Code - 1))); when X_Motion_Notify => return (Which => Pointer_Motion, Motion_Data => (X => X_Event.Mov_X, Y => X_Event.Mov_Y, Abs_X => X_Event.Mov_Root_X, Abs_Y => X_Event.Mov_Root_Y, Modifiers => Modifier_Mask_To_Set (X_Event.Mov_State))); when X_Enter_Notify => return (Which => Enter_Window, Crossing_Data => (X => X_Event.Xng_X, Y => X_Event.Xng_Y, Abs_X => X_Event.Xng_Root_X, Abs_Y => X_Event.Xng_Root_Y)); when X_Leave_Notify => return (Which => Leave_Window, Crossing_Data => (X => X_Event.Xng_X, Y => X_Event.Xng_Y, Abs_X => X_Event.Xng_Root_X, Abs_Y => X_Event.Xng_Root_Y)); when X_Focus_In => return (Which => Focus_In); when X_Focus_Out => return (Which => Focus_Out); when X_Expose => return (Which => Exposed, Expose_Data => (X => X_Event.Xps_X, Y => X_Event.Xps_Y, Width => X_Event.Xps_Width, Height => X_Event.Xps_Height, Count => X_Event.Xps_Count)); when X_Map_Notify => -- Fake up a "whole window exposed" event return (Which => Exposed, Expose_Data => (X => 0, Y => 0, Width => Win.Width, Height => Win.Height, Count => 0)); when X_Unmap_Notify => return (Which => Hidden); when X_Configure_Notify => if X_Event.Cfg_Width /= Win.Width or X_Event.Cfg_Height /= Win.Height then Win.Width := X_Event.Cfg_Width; Win.Height := X_Event.Cfg_Height; return (Which => Resized, Resize_Data => (Width => X_Event.Cfg_Width, Height => X_Event.Cfg_Height)); else -- Fake up a "whole window exposed" event return (Which => Exposed, Expose_Data => (X => 0, Y => 0, Width => X_Event.Cfg_Width, Height => X_Event.Cfg_Height, Count => 0)); end if; when X_Client_Message => declare use type Internal.Atom; begin if X_Event.Msg_Value = Internal.Delete_Window_Atom then return (Which => Close_Window); else return (Which => Unknown_Event); end if; end; when others => return (Which => Unknown_Event); end case; end Next_Event; --------------------------------------------------------------------------- -- Simple event loop with a single callback procedure Receive_Events (Win : in Window.Handle; Call : in Event_Callback) is begin -- Receive_Events -- Get events and pass them to the callback loop Call (Next_Event (Win)); end loop; end Receive_Events; --------------------------------------------------------------------------- -- Simple event loop with multiple callbacks based on event type procedure Select_Events (Win : in Window.Handle; Calls : in Event_Callback_Table) is Event : Event_Data := Next_Event (Win); begin -- Select_Events -- Get events and pass them to the selected callback, if there is one loop if Calls (Event.Which) /= No_Callback then Calls (Event.Which) (Event); end if; end loop; end Select_Events; --------------------------------------------------------------------------- end Lumen.Events;
Remove debug with for Ada.Text_IO
Remove debug with for Ada.Text_IO
Ada
isc
darkestkhan/lumen,darkestkhan/lumen2
b9d1171e78768170cb7a16959988380e15f99d70
testutil/ahven/ahven-runner.adb
testutil/ahven/ahven-runner.adb
-- -- Copyright (c) 2007, 2008 Tero Koskinen <[email protected]> -- -- 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 Ada.Command_Line; with Ahven.Listeners; with Ahven.Listeners.Basic; package body Ahven.Runner is use Ahven.Results; procedure Run_Suite (Suite : in out Framework.Test'Class; Reporter : Report_Proc) is use Ahven.Listeners.Basic; Listener : Listeners.Basic.Basic_Listener; Params : Parameters.Parameter_Info; begin Parameters.Parse_Parameters (Parameters.NORMAL_PARAMETERS, Params); Set_Output_Capture (Listener, Parameters.Capture (Params)); if Parameters.Single_Test (Params) then Framework.Execute (T => Suite, Test_Name => Parameters.Test_Name (Params), Listener => Listener, Timeout => Parameters.Timeout (Params)); else Framework.Execute (Suite, Listener, Parameters.Timeout (Params)); end if; Reporter (Listener.Main_Result, Params); if (Error_Count (Listener.Main_Result) > 0) or (Failure_Count (Listener.Main_Result) > 0) then Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end if; exception when Parameters.Invalid_Parameter => Parameters.Usage; end Run_Suite; end Ahven.Runner;
-- -- Copyright (c) 2007, 2008 Tero Koskinen <[email protected]> -- -- 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 Ada.Command_Line; with Ahven.Listeners; with Ahven.Listeners.Basic; package body Ahven.Runner is use Ahven.Results; procedure Run_Suite (Suite : in out Framework.Test'Class; Reporter : Report_Proc) is use Ahven.Listeners.Basic; Listener : Listeners.Basic.Basic_Listener; Params : Parameters.Parameter_Info; begin Parameters.Parse_Parameters (Parameters.NORMAL_PARAMETERS, Params); Set_Output_Capture (Listener, Parameters.Capture (Params)); if Parameters.Single_Test (Params) then Framework.Execute (T => Suite, Test_Name => Parameters.Test_Name (Params), Listener => Listener, Timeout => Parameters.Timeout (Params)); else Framework.Execute (Suite, Listener, Parameters.Timeout (Params)); end if; Reporter (Listener.Main_Result, Params); if (Error_Count (Listener.Main_Result) > 0) or (Failure_Count (Listener.Main_Result) > 0) then Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end if; exception when Parameters.Invalid_Parameter => Parameters.Usage; end Run_Suite; end Ahven.Runner;
Fix indentation
Fix indentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6cc74e2bbd7a3754b5e7c82bff363d89e2760776
awa/plugins/awa-storages/src/awa-storages.ads
awa/plugins/awa-storages/src/awa-storages.ads
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012, 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.Finalization; with ADO; -- == Introduction == -- The <b>Storages</b> module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Simple Storage Service. -- -- == Creating a storage == -- A data in the storage is represented by a `Storage_Ref` instance. The data itself -- can be physically stored in a file system (`FILE` mode), in the database (`DATABASE` -- mode) or on a remote server (`URL` mode). To put a file in the storage space, first create -- the storage object instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses this information -- to save the data in a file, in the database or in a remote service (in the future). -- To save a file in the store, we can use the `Save` operation of the storage service. -- It will read the file and put in in the corresponding persistent store (the database -- in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File, -- Storage => AWA.Storages.Models.DATABASE); -- -- Upon successful completion, the storage instance `Data` will be allocated a unique -- identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been designed -- to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able to read -- the file. If the storage mode of the data is `FILE`, the path of the file on -- the storage file system is used. For other storage modes, the file is saved -- in a temporary file. In that case the `Store_Local` database table is used -- to track such locally saved data. -- -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream connection is -- the most efficient mechanism. -- -- === Local file === -- To access the data by using a local file, we must define a local storage reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier. When loading locally we -- also indicate whether the file will be read or written. A file that is in `READ` mode -- can be shared by several tasks or processes. A file that is in `WRITE` mode will have -- a specific copy for the caller. An optional expiration parameter indicate when the -- local file representation can expire. -- -- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- @include awa-storages-modules.ads -- @include awa-storages-services.ads -- -- == Ada Beans == -- @include storages.xml -- -- == Model == -- [images/awa_storage_model.png] -- -- @include storage-list.xml -- @include folder-queries.xml -- @include storage-queries.xml -- package AWA.Storages is type Storage_Type is (DATABASE, FILE, URL, CACHE, TMP); type Storage_File (Storage : Storage_Type) is tagged limited private; -- Get the path to get access to the file. function Get_Path (File : in Storage_File) return String; -- Set the file path for the FILE, URL, CACHE or TMP storage. procedure Set (File : in out Storage_File; Path : in String); -- Set the file database storage identifier. procedure Set (File : in out Storage_File; Workspace : in ADO.Identifier; Store : in ADO.Identifier); private type Storage_File (Storage : Storage_Type) is limited new Ada.Finalization.Limited_Controlled with record case Storage is when DATABASE => Workspace : ADO.Identifier; Store : ADO.Identifier; when FILE | URL | CACHE | TMP => Path : Ada.Strings.Unbounded.Unbounded_String; end case; end record; overriding procedure Finalize (File : in out Storage_File); end AWA.Storages;
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012, 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.Finalization; with ADO; -- == Introduction == -- The <b>Storages</b> module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Simple Storage Service. -- -- == Creating a storage == -- A data in the storage is represented by a `Storage_Ref` instance. The data itself -- can be physically stored in a file system (`FILE` mode), in the database (`DATABASE` -- mode) or on a remote server (`URL` mode). To put a file in the storage space, first create -- the storage object instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses this information -- to save the data in a file, in the database or in a remote service (in the future). -- To save a file in the store, we can use the `Save` operation of the storage service. -- It will read the file and put in in the corresponding persistent store (the database -- in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File, -- Storage => AWA.Storages.Models.DATABASE); -- -- Upon successful completion, the storage instance `Data` will be allocated a unique -- identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been designed -- to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able to read -- the file. If the storage mode of the data is `FILE`, the path of the file on -- the storage file system is used. For other storage modes, the file is saved -- in a temporary file. In that case the `Store_Local` database table is used -- to track such locally saved data. -- -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream connection is -- the most efficient mechanism. -- -- === Local file === -- To access the data by using a local file, we must define a local storage reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier. When loading locally we -- also indicate whether the file will be read or written. A file that is in `READ` mode -- can be shared by several tasks or processes. A file that is in `WRITE` mode will have -- a specific copy for the caller. An optional expiration parameter indicate when the -- local file representation can expire. -- -- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- @include awa-storages-modules.ads -- @include awa-storages-services.ads -- -- == Ada Beans == -- @include storages.xml -- -- @include awa-storages-servlets.ads -- -- == Model == -- [images/awa_storage_model.png] -- -- @include storage-list.xml -- @include folder-queries.xml -- @include storage-queries.xml -- package AWA.Storages is type Storage_Type is (DATABASE, FILE, URL, CACHE, TMP); type Storage_File (Storage : Storage_Type) is tagged limited private; -- Get the path to get access to the file. function Get_Path (File : in Storage_File) return String; -- Set the file path for the FILE, URL, CACHE or TMP storage. procedure Set (File : in out Storage_File; Path : in String); -- Set the file database storage identifier. procedure Set (File : in out Storage_File; Workspace : in ADO.Identifier; Store : in ADO.Identifier); private type Storage_File (Storage : Storage_Type) is limited new Ada.Finalization.Limited_Controlled with record case Storage is when DATABASE => Workspace : ADO.Identifier; Store : ADO.Identifier; when FILE | URL | CACHE | TMP => Path : Ada.Strings.Unbounded.Unbounded_String; end case; end record; overriding procedure Finalize (File : in out Storage_File); end AWA.Storages;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
7d46e1fc6a669faa851ae30dc4b87935cd564849
awa/plugins/awa-mail/src/awa-mail-modules.ads
awa/plugins/awa-mail/src/awa-mail-modules.ads
----------------------------------------------------------------------- -- awa-mail -- Mail module -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects.Maps; with ASF.Applications; with AWA.Modules; with AWA.Events; with AWA.Mail.Clients; -- == Configuration == -- The *mail* module needs some properties to configure the SMTP -- server. -- -- ||mail.smtp.host||localhost||Defines the SMTP server host name|| -- ||mail.smtp.port||25||Defines the SMTP connection port|| -- ||mail.smtp.enable||1|||Defines whether sending email is enabled or not|| -- -- == Sending an email == -- Sending an email when an event is posted can be done by using -- an XML configuration. Basically, the *mail* module uses the event -- framework provided by AWA. The XML definition looks like: -- -- <on-event name="user-register"> -- <action>#{userMail.send}</action> -- <property name="template">/mail/register-user-message.xhtml</property> -- </on-event> -- -- With this definition, the mail template `/mail/register-user-message.xhtml` -- is formatted by using the event and application context when the -- `user-register` event is posted. -- -- @include awa-mail-components.ads -- @include awa-mail-components-recipients.ads -- @include awa-mail-components-messages.ads -- -- == Ada Beans == -- @include mail.xml -- package AWA.Mail.Modules is NAME : constant String := "mail"; type Mail_Module is new AWA.Modules.Module with private; type Mail_Module_Access is access all Mail_Module'Class; -- Initialize the mail module. overriding procedure Initialize (Plugin : in out Mail_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Mail_Module; Props : in ASF.Applications.Config); -- Create a new mail message. function Create_Message (Plugin : in Mail_Module) return AWA.Mail.Clients.Mail_Message_Access; -- Format and send an email. procedure Send_Mail (Plugin : in Mail_Module; Template : in String; Props : in Util.Beans.Objects.Maps.Map; Content : in AWA.Events.Module_Event'Class); -- Get the mail module instance associated with the current application. function Get_Mail_Module return Mail_Module_Access; private type Mail_Module is new AWA.Modules.Module with record Mailer : AWA.Mail.Clients.Mail_Manager_Access; end record; end AWA.Mail.Modules;
----------------------------------------------------------------------- -- awa-mail -- Mail module -- Copyright (C) 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects.Maps; with ASF.Applications; with AWA.Modules; with AWA.Events; with AWA.Mail.Clients; -- == Configuration == -- The *mail* module needs some properties to configure the SMTP -- server. -- -- |Configuration | Default | Description | -- | --------------- | --------- | ----------------------------------------------- | -- |mail.smtp.host | localhost | Defines the SMTP server host name | -- |mail.smtp.port | 25 | Defines the SMTP connection port | -- |mail.smtp.enable | 1 | Defines whether sending email is enabled or not | -- -- == Sending an email == -- Sending an email when an event is posted can be done by using -- an XML configuration. Basically, the *mail* module uses the event -- framework provided by AWA. The XML definition looks like: -- -- <on-event name="user-register"> -- <action>#{userMail.send}</action> -- <property name="template">/mail/register-user-message.xhtml</property> -- </on-event> -- -- With this definition, the mail template `/mail/register-user-message.xhtml` -- is formatted by using the event and application context when the -- `user-register` event is posted. -- -- @include awa-mail-components.ads -- @include awa-mail-components-recipients.ads -- @include awa-mail-components-messages.ads -- -- == Ada Beans == -- @include mail.xml -- package AWA.Mail.Modules is NAME : constant String := "mail"; type Mail_Module is new AWA.Modules.Module with private; type Mail_Module_Access is access all Mail_Module'Class; -- Initialize the mail module. overriding procedure Initialize (Plugin : in out Mail_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Mail_Module; Props : in ASF.Applications.Config); -- Create a new mail message. function Create_Message (Plugin : in Mail_Module) return AWA.Mail.Clients.Mail_Message_Access; -- Format and send an email. procedure Send_Mail (Plugin : in Mail_Module; Template : in String; Props : in Util.Beans.Objects.Maps.Map; Content : in AWA.Events.Module_Event'Class); -- Get the mail module instance associated with the current application. function Get_Mail_Module return Mail_Module_Access; private type Mail_Module is new AWA.Modules.Module with record Mailer : AWA.Mail.Clients.Mail_Manager_Access; end record; end AWA.Mail.Modules;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
45ceab9a431fa2489743b7316d3fbc6758fb16db
src/asf-modules-reader.adb
src/asf-modules-reader.adb
----------------------------------------------------------------------- -- asf-modules-reader -- Read module configuration files -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.IO.XML; with ASF.Applications.Main; with ASF.Navigations.Mappers; with ASF.Beans.Mappers; -- The <b>ASF.Modules.Reader</b> package reads the module configuration files -- and initializes the module. package body ASF.Modules.Reader is -- Read the module configuration file and configure the components procedure Read_Configuration (Plugin : in out Module'Class; File : in String) is Reader : Util.Serialize.IO.XML.Parser; MBean : aliased ASF.Beans.Mappers.Managed_Bean; Navigation : aliased ASF.Navigations.Mappers.Nav_Config; begin Log.Info ("Reading module configuration file {0}", File); Reader.Add_Mapping ("faces-config", ASF.Beans.Mappers.Get_Managed_Bean_Mapper); Reader.Add_Mapping ("faces-config", ASF.Navigations.Mappers.Get_Navigation_Mapper); -- Setup the managed bean context to read the <managed-bean> elements. MBean.Factory := Plugin.Factory'Unchecked_Access; ASF.Beans.Mappers.Config_Mapper.Set_Context (Ctx => Reader, Element => MBean'Unchecked_Access); -- Setup the navigation context to read the <navigation-rule> elements. Navigation.Handler := Plugin.App.Get_Navigation_Handler; ASF.Navigations.Mappers.Case_Mapper.Set_Context (Ctx => Reader, Element => Navigation'Unchecked_Access); Util.Serialize.IO.Dump (Reader, ASF.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end Read_Configuration; end ASF.Modules.Reader;
----------------------------------------------------------------------- -- asf-modules-reader -- Read module configuration files -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.IO.XML; with Util.Serialize.Mappers; with ASF.Applications.Main; with ASF.Navigations.Mappers; with ASF.Servlets.Mappers; with ASF.Beans.Mappers; -- The <b>ASF.Modules.Reader</b> package reads the module configuration files -- and initializes the module. package body ASF.Modules.Reader is -- Read the module configuration file and configure the components procedure Read_Configuration (Plugin : in out Module'Class; File : in String) is procedure Add_Mapper (Mapper : in Util.Serialize.Mappers.Mapper_Access); Reader : Util.Serialize.IO.XML.Parser; MBean : aliased ASF.Beans.Mappers.Managed_Bean; Navigation : aliased ASF.Navigations.Mappers.Nav_Config; Servlet : aliased ASF.Servlets.Mappers.Servlet_Config; procedure Add_Mapper (Mapper : in Util.Serialize.Mappers.Mapper_Access) is begin Reader.Add_Mapping ("faces-config", Mapper); Reader.Add_Mapping ("module", Mapper); Reader.Add_Mapping ("web-app", Mapper); end Add_Mapper; begin Log.Info ("Reading module configuration file {0}", File); Add_Mapper (ASF.Beans.Mappers.Get_Managed_Bean_Mapper); Add_Mapper (ASF.Navigations.Mappers.Get_Navigation_Mapper); Add_Mapper (ASF.Servlets.Mappers.Get_Servlet_Mapper); -- Setup the managed bean context to read the <managed-bean> elements. MBean.Factory := Plugin.Factory'Unchecked_Access; ASF.Beans.Mappers.Config_Mapper.Set_Context (Ctx => Reader, Element => MBean'Unchecked_Access); -- Setup the navigation context to read the <navigation-rule> elements. Navigation.Handler := Plugin.App.Get_Navigation_Handler; ASF.Navigations.Mappers.Case_Mapper.Set_Context (Ctx => Reader, Element => Navigation'Unchecked_Access); Servlet.Handler := Plugin.App.all'Unchecked_Access; ASF.Servlets.Mappers.Servlet_Mapper.Set_Context (Ctx => Reader, Element => Servlet'Unchecked_Access); Util.Serialize.IO.Dump (Reader, ASF.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end Read_Configuration; end ASF.Modules.Reader;
Read the servlet configuration when reading a module configuration file
Read the servlet configuration when reading a module configuration file
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
b8d3655c1b44345b7ad4b5da601cd2fc40f866a8
samples/import.adb
samples/import.adb
----------------------------------------------------------------------- -- import -- Import some HTML content and generate Wiki text -- 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.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Characters.Conversions; with GNAT.Command_Line; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings.Transforms; with Wiki.Filters.Html; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Render.Wiki; with Wiki.Documents; with Wiki.Parsers; procedure Import is use GNAT.Command_Line; use Ada.Strings.Unbounded; use Ada.Characters.Conversions; procedure Usage; function Is_Url (Name : in String) return Boolean; procedure Parse_Url (Url : in String); procedure Parse (Content : in String); Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Count : Natural := 0; Html_Mode : Boolean := True; Wiki_Mode : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; procedure Usage is begin Ada.Text_IO.Put_Line ("Import HTML into a target Wiki format"); Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-d] [-c] {URL | file}"); Ada.Text_IO.Put_Line (" -t Convert to text only"); Ada.Text_IO.Put_Line (" -m Convert to Markdown"); Ada.Text_IO.Put_Line (" -M Convert to Mediawiki"); Ada.Text_IO.Put_Line (" -d Convert to Dotclear"); Ada.Text_IO.Put_Line (" -c Convert to Creole"); end Usage; procedure Parse (Content : in String) is Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Engine.Add_Filter (Html_Filter'Unchecked_Access); if Wiki_Mode then declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Engine.Set_Syntax (Wiki.SYNTAX_HTML); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access, Syntax); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; elsif Html_Mode then declare Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; else declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; end if; end Parse; procedure Parse_Url (Url : in String) is Command : constant String := "wget -q -O - " & Url; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Pipe.Open (Command); Buffer.Initialize (null, Pipe'Unchecked_Access, 1024 * 1024); Buffer.Read (Content); Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Ada.Text_IO.Put_Line (Command & " exited with status " & Integer'Image (Pipe.Get_Exit_Status)); else Parse (To_String (Content)); end if; end Parse_Url; function Is_Url (Name : in String) return Boolean is begin if Name'Length <= 9 then return False; else return Name (Name'First .. Name'First + 6) = "http://" or Name (Name'First .. Name'First + 7) = "https://"; end if; end Is_Url; begin loop case Getopt ("m M d c t f:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; Wiki_Mode := True; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; Wiki_Mode := True; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; Wiki_Mode := True; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; Wiki_Mode := True; when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter); begin Html_Filter.Hide (Wiki.Html_Tag'Value (Value & "_TAG")); exception when Constraint_Error => Ada.Text_IO.Put_Line ("Invalid tag " & Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; if Is_Url (Name) then Parse_Url (Name); else Util.Files.Read_File (Name, Data); Parse (To_String (Data)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Import;
----------------------------------------------------------------------- -- import -- Import some HTML content and generate Wiki text -- 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.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Characters.Conversions; with GNAT.Command_Line; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings.Transforms; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Render.Wiki; with Wiki.Documents; with Wiki.Parsers; procedure Import is use GNAT.Command_Line; use Ada.Strings.Unbounded; use Ada.Characters.Conversions; procedure Usage; function Is_Url (Name : in String) return Boolean; procedure Parse_Url (Url : in String); procedure Parse (Content : in String); Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Count : Natural := 0; Html_Mode : Boolean := True; Wiki_Mode : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; procedure Usage is begin Ada.Text_IO.Put_Line ("Import HTML into a target Wiki format"); Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-d] [-c] {URL | file}"); Ada.Text_IO.Put_Line (" -t Convert to text only"); Ada.Text_IO.Put_Line (" -m Convert to Markdown"); Ada.Text_IO.Put_Line (" -M Convert to Mediawiki"); Ada.Text_IO.Put_Line (" -d Convert to Dotclear"); Ada.Text_IO.Put_Line (" -c Convert to Creole"); end Usage; procedure Parse (Content : in String) is Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); if Wiki_Mode then declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Engine.Set_Syntax (Wiki.SYNTAX_HTML); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access, Syntax); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; elsif Html_Mode then declare Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; else declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; end if; end Parse; procedure Parse_Url (Url : in String) is Command : constant String := "wget -q -O - " & Url; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Pipe.Open (Command); Buffer.Initialize (null, Pipe'Unchecked_Access, 1024 * 1024); Buffer.Read (Content); Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Ada.Text_IO.Put_Line (Command & " exited with status " & Integer'Image (Pipe.Get_Exit_Status)); else Parse (To_String (Content)); end if; end Parse_Url; function Is_Url (Name : in String) return Boolean is begin if Name'Length <= 9 then return False; else return Name (Name'First .. Name'First + 6) = "http://" or Name (Name'First .. Name'First + 7) = "https://"; end if; end Is_Url; begin loop case Getopt ("m M d c t f:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; Wiki_Mode := True; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; Wiki_Mode := True; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; Wiki_Mode := True; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; Wiki_Mode := True; when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter); begin Html_Filter.Hide (Wiki.Html_Tag'Value (Value & "_TAG")); exception when Constraint_Error => Ada.Text_IO.Put_Line ("Invalid tag " & Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; if Is_Url (Name) then Parse_Url (Name); else Util.Files.Read_File (Name, Data); Parse (To_String (Data)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Import;
Add the TOC filter
Add the TOC filter
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
a3f7c5aeca2a2ff21d52b81caef83e21b7fe760d
awa/regtests/awa-commands-tests.adb
awa/regtests/awa-commands-tests.adb
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Test_Caller; with Util.Log.Loggers; package body AWA.Commands.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands.Tests"); package Caller is new Util.Test_Caller (Test, "Commands"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Commands.Start_Stop", Test_Start_Stop'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (tables)", Test_List_Tables'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (users)", Test_List_Users'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (sessions)", Test_List_Sessions'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (jobs)", Test_List_Jobs'Access); Caller.Add_Test (Suite, "Test AWA.Commands.Info (secure configuration)", Test_Secure_Configuration'Access); Caller.Add_Test (Suite, "Test AWA.Commands.Info (verbose)", Test_Verbose_Command'Access); end Add_Tests; -- ------------------------------ -- Execute the command and get the output in a string. -- ------------------------------ procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0) is P : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; begin if Input'Length > 0 then Log.Info ("Execute: {0} < {1}", Command, Input); elsif Output'Length > 0 then Log.Info ("Execute: {0} > {1}", Command, Output); else Log.Info ("Execute: {0}", Command); end if; P.Set_Input_Stream (Input); P.Set_Output_Stream (Output); P.Open (Command, Util.Processes.READ_ALL); -- Write on the process input stream. Result := Ada.Strings.Unbounded.Null_Unbounded_String; Buffer.Initialize (P'Unchecked_Access, 8192); Buffer.Read (Result); P.Close; Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Result)); Log.Info ("Command result: {0}", Result); Util.Tests.Assert_Equals (T, Status, P.Get_Exit_Status, "Command '" & Command & "' failed"); end Execute; -- ------------------------------ -- Test start and stop command. -- ------------------------------ procedure Test_Start_Stop (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); task Start_Server is entry Start; entry Wait (Result : out Ada.Strings.Unbounded.Unbounded_String); end Start_Server; task body Start_Server is Output : Ada.Strings.Unbounded.Unbounded_String; begin accept Start do null; end Start; begin T.Execute ("bin/awa_command -c " & Config & " start -m 26123", "", "", Output, 0); exception when others => Output := Ada.Strings.Unbounded.To_Unbounded_String ("* exception *"); end; accept Wait (Result : out Ada.Strings.Unbounded.Unbounded_String) do Result := Output; end Wait; end Start_Server; Result : Ada.Strings.Unbounded.Unbounded_String; begin -- Launch the 'start' command in a separate task because the command will hang. Start_Server.Start; delay 5.0; -- Launch the 'stop' command, this should terminate the 'start' command. T.Execute ("bin/awa_command -c " & Config & " stop -m 26123", "", "", Result, 0); -- Wait for the task result. Start_Server.Wait (Result); Util.Tests.Assert_Matches (T, "Starting...", Result, "AWA start command output"); end Test_Start_Stop; procedure Test_List_Tables (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -t", "", "", Result, 0); Util.Tests.Assert_Matches (T, "awa_audit *[0-9]+", Result, "Missing awa_audit"); Util.Tests.Assert_Matches (T, "awa_session *[0-9]+", Result, "Missing awa_session"); Util.Tests.Assert_Matches (T, "entity_type *[0-9]+", Result, "Missing entity_type"); Util.Tests.Assert_Matches (T, "awa_wiki_page *[0-9]+", Result, "Missing awa_wiki_page"); end Test_List_Tables; -- ------------------------------ -- Test the list -u command. -- ------------------------------ procedure Test_List_Users (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -u", "", "", Result, 0); Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user"); Util.Tests.Assert_Matches (T, "[email protected]", Result, "Missing email"); end Test_List_Users; -- ------------------------------ -- Test the list -s command. -- ------------------------------ procedure Test_List_Sessions (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -s", "", "", Result, 0); Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user"); end Test_List_Sessions; -- ------------------------------ -- Test the list -j command. -- ------------------------------ procedure Test_List_Jobs (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -j", "", "", Result, 0); Util.Tests.Assert_Matches (T, "S_FACTORY", Result, "Missing factory"); Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user"); end Test_List_Jobs; -- ------------------------------ -- Test the command with a secure keystore configuration. -- ------------------------------ procedure Test_Secure_Configuration (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Keystore : constant String := Util.Tests.Get_Parameter ("test_keystore_file"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " info --keystore " & Keystore & " --password=unit-test-password", "", "", Result, 0); Util.Tests.Assert_Matches (T, "app_name *AWA Secure Demo", Result, "Secure property not accessed"); end Test_Secure_Configuration; -- ------------------------------ -- Test the command with various logging options. -- ------------------------------ procedure Test_Verbose_Command (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -v -c " & Config & " info ", "", "", Result, 0); Util.Tests.Assert_Matches (T, "INFO - AWA.Applications", Result, "Missing log message"); end Test_Verbose_Command; end AWA.Commands.Tests;
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Test_Caller; with Util.Log.Loggers; package body AWA.Commands.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands.Tests"); package Caller is new Util.Test_Caller (Test, "Commands"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Commands.Start_Stop", Test_Start_Stop'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (tables)", Test_List_Tables'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (users)", Test_List_Users'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (sessions)", Test_List_Sessions'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (jobs)", Test_List_Jobs'Access); Caller.Add_Test (Suite, "Test AWA.Commands.Info (secure configuration 1)", Test_Secure_Configuration'Access); Caller.Add_Test (Suite, "Test AWA.Commands.Info (secure configuration 2)", Test_Secure_Configuration_2'Access); Caller.Add_Test (Suite, "Test AWA.Commands.Info (verbose)", Test_Verbose_Command'Access); end Add_Tests; -- ------------------------------ -- Execute the command and get the output in a string. -- ------------------------------ procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0) is P : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; begin if Input'Length > 0 then Log.Info ("Execute: {0} < {1}", Command, Input); elsif Output'Length > 0 then Log.Info ("Execute: {0} > {1}", Command, Output); else Log.Info ("Execute: {0}", Command); end if; P.Set_Input_Stream (Input); P.Set_Output_Stream (Output); P.Open (Command, Util.Processes.READ_ALL); -- Write on the process input stream. Result := Ada.Strings.Unbounded.Null_Unbounded_String; Buffer.Initialize (P'Unchecked_Access, 8192); Buffer.Read (Result); P.Close; Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Result)); Log.Info ("Command result: {0}", Result); Util.Tests.Assert_Equals (T, Status, P.Get_Exit_Status, "Command '" & Command & "' failed"); end Execute; -- ------------------------------ -- Test start and stop command. -- ------------------------------ procedure Test_Start_Stop (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); task Start_Server is entry Start; entry Wait (Result : out Ada.Strings.Unbounded.Unbounded_String); end Start_Server; task body Start_Server is Output : Ada.Strings.Unbounded.Unbounded_String; begin accept Start do null; end Start; begin T.Execute ("bin/awa_command -c " & Config & " start -m 26123", "", "", Output, 0); exception when others => Output := Ada.Strings.Unbounded.To_Unbounded_String ("* exception *"); end; accept Wait (Result : out Ada.Strings.Unbounded.Unbounded_String) do Result := Output; end Wait; end Start_Server; Result : Ada.Strings.Unbounded.Unbounded_String; begin -- Launch the 'start' command in a separate task because the command will hang. Start_Server.Start; delay 5.0; -- Launch the 'stop' command, this should terminate the 'start' command. T.Execute ("bin/awa_command -c " & Config & " stop -m 26123", "", "", Result, 0); -- Wait for the task result. Start_Server.Wait (Result); Util.Tests.Assert_Matches (T, "Starting...", Result, "AWA start command output"); end Test_Start_Stop; procedure Test_List_Tables (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -t", "", "", Result, 0); Util.Tests.Assert_Matches (T, "awa_audit *[0-9]+", Result, "Missing awa_audit"); Util.Tests.Assert_Matches (T, "awa_session *[0-9]+", Result, "Missing awa_session"); Util.Tests.Assert_Matches (T, "entity_type *[0-9]+", Result, "Missing entity_type"); Util.Tests.Assert_Matches (T, "awa_wiki_page *[0-9]+", Result, "Missing awa_wiki_page"); end Test_List_Tables; -- ------------------------------ -- Test the list -u command. -- ------------------------------ procedure Test_List_Users (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -u", "", "", Result, 0); Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user"); Util.Tests.Assert_Matches (T, "[email protected]", Result, "Missing email"); end Test_List_Users; -- ------------------------------ -- Test the list -s command. -- ------------------------------ procedure Test_List_Sessions (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -s", "", "", Result, 0); Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user"); end Test_List_Sessions; -- ------------------------------ -- Test the list -j command. -- ------------------------------ procedure Test_List_Jobs (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -j", "", "", Result, 0); Util.Tests.Assert_Matches (T, "S_FACTORY", Result, "Missing factory"); Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user"); end Test_List_Jobs; -- ------------------------------ -- Test the command with a secure keystore configuration. -- ------------------------------ procedure Test_Secure_Configuration (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Keystore : constant String := Util.Tests.Get_Parameter ("test_keystore_file"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " info --keystore " & Keystore & " --password=unit-test-password", "", "", Result, 0); Util.Tests.Assert_Matches (T, "app_name *AWA Secure Demo", Result, "Secure property not accessed"); end Test_Secure_Configuration; -- ------------------------------ -- Test the command with a secure keystore configuration. -- ------------------------------ procedure Test_Secure_Configuration_2 (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_secure_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " info", "", "", Result, 0); Util.Tests.Assert_Matches (T, "app_name *AWA Secure Demo", Result, "Secure property not accessed"); Util.Tests.Assert_Matches (T, "users.auth_key *auth-", Result, "Secure property not accessed"); Util.Tests.Assert_Matches (T, "users.server_id *[123]0", Result, "Secure property not accessed"); end Test_Secure_Configuration_2; -- ------------------------------ -- Test the command with various logging options. -- ------------------------------ procedure Test_Verbose_Command (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -v -c " & Config & " info ", "", "", Result, 0); Util.Tests.Assert_Matches (T, "INFO : Using application search dir:", Result, "Missing log message"); end Test_Verbose_Command; end AWA.Commands.Tests;
Implement Test_Secure_Configuration_2 to check another setup with secure configuration
Implement Test_Secure_Configuration_2 to check another setup with secure configuration
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
60a6c6d3844987b8e1ae91ad713038529a34f48b
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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; -- == Events == -- The <tt>wikis</tt> exposes a number of events which are posted when some action -- are performed at the service level. -- -- === 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"; 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 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; 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; end record; end AWA.Wikis.Modules;
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- 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 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; -- == Events == -- The <tt>wikis</tt> exposes a number of events which are posted when some action -- are performed at the service level. -- -- === 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; 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;
Declare Get_Page_Prefix function and PARAM_PAGE_PREFIX constant
Declare Get_Page_Prefix function and PARAM_PAGE_PREFIX constant
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
60dd7be718d8d5090460ae07ad71e2dcaa15f948
src/gen-model-list.ads
src/gen-model-list.ads
----------------------------------------------------------------------- -- gen-model-list -- List bean interface for model objects -- Copyright (C) 2009, 2010, 2011, 2012, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Gen.Model; with Ada.Containers.Vectors; with Ada.Iterator_Interfaces; generic type T is new Gen.Model.Definition with private; type T_Access is access all T'Class; package Gen.Model.List is -- Compare the two definitions. function "<" (Left, Right : in T_Access) return Boolean; package Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => T_Access, "=" => "="); package Sorting is new Vectors.Generic_Sorting; subtype Cursor is Vectors.Cursor; subtype Vector is Vectors.Vector; function Has_Element (Position : Cursor) return Boolean renames Vectors.Has_Element; function Element (Position : Cursor) return T_Access renames Vectors.Element; procedure Next (Position : in out Cursor) renames Vectors.Next; type List_Definition is limited new Util.Beans.Basic.List_Bean with private with Default_Iterator => Iterate, Iterator_Element => T_Access, Constant_Indexing => Element_Value; package List_Iterator is new Ada.Iterator_Interfaces (Cursor, Has_Element); -- Make an iterator for the list. function Iterate (Container : in List_Definition) return List_Iterator.Forward_Iterator'Class; -- Get the iterator element. function Element_Value (Container : in List_Definition; Pos : in Cursor) return T_Access; -- Get the first item of the list function First (Def : List_Definition) return Cursor; -- Get the number of elements in the list. overriding function Get_Count (From : List_Definition) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Definition; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : List_Definition) return UBO.Object; -- 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 : List_Definition; Name : String) return UBO.Object; -- Append the item in the list procedure Append (Def : in out List_Definition; Item : in T_Access); -- Sort the list of items on their names. procedure Sort (List : in out List_Definition); generic with function "<" (Left, Right : T_Access) return Boolean is <>; procedure Sort_On (List : in out List_Definition); -- Find a definition given the name. -- Returns the definition object or null. function Find (Def : in List_Definition; Name : in String) return T_Access; -- Iterate over the elements of the list executing the <tt>Process</tt> procedure. procedure Iterate (Def : in List_Definition; Process : not null access procedure (Item : in T_Access)); private type List_Definition_Access is access all List_Definition; type List_Definition is limited new Util.Beans.Basic.List_Bean with record Self : List_Definition_Access := List_Definition'Unchecked_Access; Nodes : Vectors.Vector; Row : Natural := 0; Value_Bean : UBO.Object; end record; type Iterator is limited new List_Iterator.Forward_Iterator with record List : List_Definition_Access; end record; overriding function First (Object : Iterator) return Cursor; overriding function Next (Object : Iterator; Pos : Cursor) return Cursor; end Gen.Model.List;
----------------------------------------------------------------------- -- gen-model-list -- List bean interface for model objects -- Copyright (C) 2009, 2010, 2011, 2012, 2018, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Ada.Containers.Vectors; with Ada.Iterator_Interfaces; generic type T is new Gen.Model.Definition with private; type T_Access is access all T'Class; package Gen.Model.List is -- Compare the two definitions. function "<" (Left, Right : in T_Access) return Boolean; package Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => T_Access, "=" => "="); package Sorting is new Vectors.Generic_Sorting; subtype Cursor is Vectors.Cursor; subtype Vector is Vectors.Vector; function Has_Element (Position : Cursor) return Boolean renames Vectors.Has_Element; function Element (Position : Cursor) return T_Access renames Vectors.Element; procedure Next (Position : in out Cursor) renames Vectors.Next; type List_Definition is limited new Util.Beans.Basic.List_Bean with private with Default_Iterator => Iterate, Iterator_Element => T_Access, Constant_Indexing => Element_Value; package List_Iterator is new Ada.Iterator_Interfaces (Cursor, Has_Element); -- Make an iterator for the list. function Iterate (Container : in List_Definition) return List_Iterator.Forward_Iterator'Class; -- Get the iterator element. function Element_Value (Container : in List_Definition; Pos : in Cursor) return T_Access; -- Get the first item of the list function First (Def : List_Definition) return Cursor; -- Get the number of elements in the list. overriding function Get_Count (From : List_Definition) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Definition; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : List_Definition) return UBO.Object; -- 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 : List_Definition; Name : String) return UBO.Object; -- Append the item in the list procedure Append (Def : in out List_Definition; Item : in T_Access); -- Sort the list of items on their names. procedure Sort (List : in out List_Definition); generic with function "<" (Left, Right : T_Access) return Boolean is <>; procedure Sort_On (List : in out List_Definition); -- Find a definition given the name. -- Returns the definition object or null. function Find (Def : in List_Definition; Name : in String) return T_Access; -- Iterate over the elements of the list executing the <tt>Process</tt> procedure. procedure Iterate (Def : in List_Definition; Process : not null access procedure (Item : in T_Access)); private type List_Definition_Access is access all List_Definition; type List_Definition is limited new Util.Beans.Basic.List_Bean with record Self : List_Definition_Access := List_Definition'Unchecked_Access; Nodes : Vectors.Vector; Row : Natural := 0; Value_Bean : UBO.Object; end record; type Iterator is limited new List_Iterator.Forward_Iterator with record List : List_Definition_Access; end record; overriding function First (Object : Iterator) return Cursor; overriding function Next (Object : Iterator; Pos : Cursor) return Cursor; end Gen.Model.List;
Fix compilation warning with GCC 12: remove unused with clause for an ancestor
Fix compilation warning with GCC 12: remove unused with clause for an ancestor
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
06d702855785a2fb1b7891973e623a2178ab39f4
src/gen-model-enums.adb
src/gen-model-enums.adb
----------------------------------------------------------------------- -- gen-model-enums -- Enum definitions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Model.Enums is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Value_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "value" then return Util.Beans.Objects.To_Object (From.Number); else return Definition (From).Get_Value (Name); end if; 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 : Enum_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "values" then return From.Values_Bean; elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (True); else return Mappings.Mapping_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Enum_Definition) is begin O.Target := O.Type_Name; null; end Prepare; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Enum_Definition) is begin O.Values_Bean := Util.Beans.Objects.To_Object (O.Values'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an enum value to this enum definition and return the new value. -- ------------------------------ procedure Add_Value (Enum : in out Enum_Definition; Name : in String; Value : out Value_Definition_Access) is begin Value := new Value_Definition; Value.Name := To_Unbounded_String (Name); Value.Number := Enum.Values.Get_Count; Enum.Values.Append (Value); end Add_Value; -- ------------------------------ -- Create an enum with the given name. -- ------------------------------ function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access is Enum : constant Enum_Definition_Access := new Enum_Definition; begin Enum.Name := Name; declare Pos : constant Natural := Index (Enum.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Enum.Pkg_Name := Unbounded_Slice (Enum.Name, 1, Pos - 1); Enum.Type_Name := Unbounded_Slice (Enum.Name, Pos + 1, Length (Enum.Name)); else Enum.Pkg_Name := To_Unbounded_String ("ADO"); Enum.Type_Name := Enum.Name; end if; end; return Enum; end Create_Enum; end Gen.Model.Enums;
----------------------------------------------------------------------- -- gen-model-enums -- Enum definitions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Model.Enums is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Value_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "value" then return Util.Beans.Objects.To_Object (From.Number); else return Definition (From).Get_Value (Name); end if; 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 : Enum_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "values" then return From.Values_Bean; elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (True); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); else return Mappings.Mapping_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Enum_Definition) is begin O.Target := O.Type_Name; null; end Prepare; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Enum_Definition) is begin O.Values_Bean := Util.Beans.Objects.To_Object (O.Values'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an enum value to this enum definition and return the new value. -- ------------------------------ procedure Add_Value (Enum : in out Enum_Definition; Name : in String; Value : out Value_Definition_Access) is begin Value := new Value_Definition; Value.Name := To_Unbounded_String (Name); Value.Number := Enum.Values.Get_Count; Enum.Values.Append (Value); end Add_Value; -- ------------------------------ -- Create an enum with the given name. -- ------------------------------ function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access is Enum : constant Enum_Definition_Access := new Enum_Definition; begin Enum.Name := Name; declare Pos : constant Natural := Index (Enum.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Enum.Pkg_Name := Unbounded_Slice (Enum.Name, 1, Pos - 1); Enum.Type_Name := Unbounded_Slice (Enum.Name, Pos + 1, Length (Enum.Name)); else Enum.Pkg_Name := To_Unbounded_String ("ADO"); Enum.Type_Name := Enum.Name; end if; end; return Enum; end Create_Enum; end Gen.Model.Enums;
Add support for the sqlType bean attribute
Add support for the sqlType bean attribute
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
fd6431387250d654a3aa60c3dd05ba3bd1fdf4ed
src/wiki-plugins.ads
src/wiki-plugins.ads
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- Copyright (C) 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Filters; with Wiki.Strings; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Plugin_Context; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; type Plugin_Factory is limited interface; type Plugin_Factory_Access is access all Plugin_Factory'Class; -- Find a plugin knowing its name. function Find (Factory : in Plugin_Factory; Name : in String) return Wiki_Plugin_Access is abstract; type Plugin_Context is limited record Previous : access Plugin_Context; Filters : Wiki.Filters.Filter_Chain; Factory : Plugin_Factory_Access; Variables : Wiki.Attributes.Attribute_List; Syntax : Wiki.Wiki_Syntax; Ident : Wiki.Strings.UString; Is_Hidden : Boolean := False; Is_Included : Boolean := False; end record; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is abstract; end Wiki.Plugins;
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- Copyright (C) 2016, 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.Attributes; with Wiki.Documents; with Wiki.Filters; with Wiki.Strings; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Plugin_Context; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; type Plugin_Factory is limited interface; type Plugin_Factory_Access is access all Plugin_Factory'Class; -- Find a plugin knowing its name. function Find (Factory : in Plugin_Factory; Name : in String) return Wiki_Plugin_Access is abstract; type Plugin_Context is limited record Previous : access Plugin_Context; Filters : Wiki.Filters.Filter_Chain; Factory : Plugin_Factory_Access; Variables : Wiki.Attributes.Attribute_List; Syntax : Wiki.Wiki_Syntax; Ident : Wiki.Strings.UString; Is_Hidden : Boolean := False; Is_Included : Boolean := False; end record; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in out Plugin_Context) is abstract; end Wiki.Plugins;
Change the Context parameter to 'in out' because we may need to access the filters
Change the Context parameter to 'in out' because we may need to access the filters
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
576b2472157660f92cdb050b256e2ab4b620155b
src/base/beans/util-beans-objects-records.ads
src/base/beans/util-beans-objects-records.ads
----------------------------------------------------------------------- -- Util.Beans.Objects.Records -- Generic Typed Data Representation -- 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. ----------------------------------------------------------------------- generic type Element_Type is private; package Util.Beans.Objects.Records is type Element_Type_Access is access all Element_Type; -- Create an object which holds a record of the type <b>Element_Type</b>. function Create return Object; -- Create an object which is initialized with the given value. function To_Object (Value : in Element_Type) return Object; -- Returns the element function To_Element (Value : in Object) return Element_Type; -- Returns an access to the element. function To_Element_Access (Value : in Object) return Element_Type_Access; private type Element_Proxy is new Proxy with record Value : aliased Element_Type; end record; end Util.Beans.Objects.Records;
----------------------------------------------------------------------- -- util-beans-objects-records -- Generic Typed Data Representation -- Copyright (C) 2011, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- generic type Element_Type is private; package Util.Beans.Objects.Records is type Element_Type_Access is access all Element_Type; -- Create an object which holds a record of the type <b>Element_Type</b>. function Create return Object; -- Create an object which is initialized with the given value. function To_Object (Value : in Element_Type) return Object; -- Returns the element function To_Element (Value : in Object) return Element_Type; -- Returns an access to the element. function To_Element_Access (Value : in Object) return Element_Type_Access; private type Element_Proxy is new Proxy with record Value : aliased Element_Type; end record; end Util.Beans.Objects.Records;
Update documentation
Update documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3bb652c8fd8f3e0ad1e6bf7c735d79b481661c85
src/sys/os-linux32/util-systems-constants.ads
src/sys/os-linux32/util-systems-constants.ads
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Constants is pragma Pure; -- Flags used when opening a file with open/creat. O_RDONLY : constant Interfaces.C.int := 8#000000#; O_WRONLY : constant Interfaces.C.int := 8#000001#; O_RDWR : constant Interfaces.C.int := 8#000002#; O_CREAT : constant Interfaces.C.int := 8#000100#; O_EXCL : constant Interfaces.C.int := 8#000200#; O_TRUNC : constant Interfaces.C.int := 8#001000#; O_APPEND : constant Interfaces.C.int := 8#002000#; O_CLOEXEC : constant Interfaces.C.int := 8#2000000#; O_SYNC : constant Interfaces.C.int := 8#4010000#; O_NONBLOCK : constant Interfaces.C.int := 8#004000#; -- Flags used by fcntl F_SETFL : constant Interfaces.C.int := 4; F_GETFL : constant Interfaces.C.int := 3; FD_CLOEXEC : constant Interfaces.C.int := 1; -- Flags used by dlopen RTLD_LAZY : constant Interfaces.C.int := 8#000001#; RTLD_NOW : constant Interfaces.C.int := 8#000002#; RTLD_NOLOAD : constant Interfaces.C.int := 8#000004#; RTLD_DEEPBIND : constant Interfaces.C.int := 8#000010#; RTLD_GLOBAL : constant Interfaces.C.int := 8#000400#; RTLD_LOCAL : constant Interfaces.C.int := 8#000000#; RTLD_NODELETE : constant Interfaces.C.int := 8#010000#; DLL_OPTIONS : constant String := "-ldl"; end Util.Systems.Constants;
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Constants is pragma Pure; -- Flags used when opening a file with open/creat. O_RDONLY : constant Interfaces.C.int := 8#000000#; O_WRONLY : constant Interfaces.C.int := 8#000001#; O_RDWR : constant Interfaces.C.int := 8#000002#; O_CREAT : constant Interfaces.C.int := 8#000100#; O_EXCL : constant Interfaces.C.int := 8#000200#; O_TRUNC : constant Interfaces.C.int := 8#001000#; O_APPEND : constant Interfaces.C.int := 8#002000#; O_CLOEXEC : constant Interfaces.C.int := 8#2000000#; O_SYNC : constant Interfaces.C.int := 8#4010000#; O_NONBLOCK : constant Interfaces.C.int := 8#004000#; -- Flags used by fcntl F_SETFL : constant Interfaces.C.int := 4; F_GETFL : constant Interfaces.C.int := 3; FD_CLOEXEC : constant Interfaces.C.int := 1; -- Flags used by dlopen RTLD_LAZY : constant Interfaces.C.int := 8#000001#; RTLD_NOW : constant Interfaces.C.int := 8#000002#; RTLD_NOLOAD : constant Interfaces.C.int := 8#000004#; RTLD_DEEPBIND : constant Interfaces.C.int := 8#000010#; RTLD_GLOBAL : constant Interfaces.C.int := 8#000400#; RTLD_LOCAL : constant Interfaces.C.int := 8#000000#; RTLD_NODELETE : constant Interfaces.C.int := 8#010000#; DLL_OPTIONS : constant String := "-ldl"; SYMBOL_PREFIX : constant String := ""; end Util.Systems.Constants;
Declare SYMBOL_PREFIX
Declare SYMBOL_PREFIX
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d6a53bc06a5b1db634215a3f14343ae76dc6fc89
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_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT, F_MODE, F_FRAME_ID, F_RANGE_ADDR, F_FRAME_ADDR); type Notice_Type is (N_HELP, 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); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT, F_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); 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;
Add N_INFO notice
Add N_INFO notice
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1e75936ccb58b658082f0814dde84640af04bb47
src/gen-artifacts-docs-googlecode.adb
src/gen-artifacts-docs-googlecode.adb
----------------------------------------------------------------------- -- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Googlecode is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is begin Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_NewLine then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line); end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Write_Line (File, "{{{"); when L_END_CODE => Formatter.Write_Line (File, "}}}"); when L_TEXT => Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Write_Line (File, "= " & Line.Content & " ="); when L_HEADER_2 => Formatter.Write_Line (File, "== " & Line.Content & " =="); when L_HEADER_3 => Formatter.Write_Line (File, "=== " & Line.Content & " ==="); when L_HEADER_4 => Formatter.Write_Line (File, "==== " & Line.Content & " ===="); when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[https://github.com/stcarrez/dynamo Generated by Dynamo] from _" & Source & "_"); end Finish_Document; end Gen.Artifacts.Docs.Googlecode;
----------------------------------------------------------------------- -- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Googlecode is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line); end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Write_Line (File, "{{{"); when L_END_CODE => Formatter.Write_Line (File, "}}}"); when L_TEXT => Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Write_Line (File, "= " & Line.Content & " ="); when L_HEADER_2 => Formatter.Write_Line (File, "== " & Line.Content & " =="); when L_HEADER_3 => Formatter.Write_Line (File, "=== " & Line.Content & " ==="); when L_HEADER_4 => Formatter.Write_Line (File, "==== " & Line.Content & " ===="); when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter, Document); begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[https://github.com/stcarrez/dynamo Generated by Dynamo] from _" & Source & "_"); end Finish_Document; end Gen.Artifacts.Docs.Googlecode;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
0533a47f03a193dc6eef1a1aaf207bd779e5ba0e
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; with Util.Refs; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; type Node_List_Ref is private; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; Parent : Node_Type_Access; when N_PREFORMAT => Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Append a node to the node list. procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)); -- Returns True if the list reference is empty. function Is_Empty (List : in Node_List_Ref) return Boolean; -- Get the number of nodes in the list. function Length (List : in Node_List_Ref) return Natural; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited new Util.Refs.Ref_Entity with record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Finalize the node list to release the allocated memory. overriding procedure Finalize (List : in out Node_List); -- Append a node to the node list. -- procedure Append (Into : in out Node_List; -- Node : in Node_Type_Access); package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access); type Node_List_Ref is new Node_List_Refs.Ref with null record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; with Util.Refs; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_TOC_DISPLAY, N_PARAGRAPH, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; type Node_List_Ref is private; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; Parent : Node_Type_Access; when N_PREFORMAT => Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Append a node to the node list. procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)); -- Returns True if the list reference is empty. function Is_Empty (List : in Node_List_Ref) return Boolean; -- Get the number of nodes in the list. function Length (List : in Node_List_Ref) return Natural; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited new Util.Refs.Ref_Entity with record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Finalize the node list to release the allocated memory. overriding procedure Finalize (List : in out Node_List); -- Append a node to the node list. -- procedure Append (Into : in out Node_List; -- Node : in Node_Type_Access); package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access); type Node_List_Ref is new Node_List_Refs.Ref with null record; end Wiki.Nodes;
Add N_TOC_DISPLAY to display the table of content at well defined locations
Add N_TOC_DISPLAY to display the table of content at well defined locations
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
71aca6d9228f3cfa563f1171b6f1445cad61c480
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; with ASF.Tests; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with Security.Contexts; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid"); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous (""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; end AWA.Blogs.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; with ASF.Tests; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with Security.Contexts; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)", Test_Admin_List_Comments'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid"); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous (""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; -- ------------------------------ -- Test listing the blog comments. -- ------------------------------ procedure Test_Admin_List_Comments (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident, "blog-list-comments.html"); ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply, "Blog admin comments page is invalid"); end Test_Admin_List_Comments; end AWA.Blogs.Tests;
Implement Test_Admin_List_Comments to test the list of comments
Implement Test_Admin_List_Comments to test the list of comments
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
de0fbee698cd03ca69c9c87f31161ed17c38504f
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- There are basically two steps that an application must implement. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-security
7bb458b7da1e8818d88ccaf1c0901b53dd7e408c
awa/plugins/awa-jobs/src/awa-jobs-services.adb
awa/plugins/awa-jobs/src/awa-jobs-services.adb
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.Tools; with Util.Log.Loggers; with Ada.Tags; with Ada.Calendar; with Ada.Unchecked_Deallocation; with ADO.Sessions.Entities; with AWA.Users.Models; with AWA.Events.Models; with AWA.Services.Contexts; with AWA.Jobs.Modules; with AWA.Applications; with AWA.Events.Services; with AWA.Modules; package body AWA.Jobs.Services is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services"); -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Integer) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object) is begin Job.Props.Include (Name, Value); Job.Props_Modified := True; end Set_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String is Value : constant Util.Beans.Objects.Object := Job.Get_Parameter (Name); begin return Util.Beans.Objects.To_String (Value); end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value as an integer. -- If the parameter is not defined, return the default value passed in <b>Default</b>. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String; Default : in Integer) return Integer is Pos : constant Util.Beans.Objects.Maps.Cursor := Job.Props.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then declare Value : constant Util.Beans.Objects.Object := Util.Beans.Objects.Maps.Element (Pos); begin if Util.Beans.Objects.Is_Null (Value) then return Default; else return Util.Beans.Objects.To_Integer (Value); end if; end; else return Default; end if; end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object is begin return Job.Props.Element (Name); end Get_Parameter; -- ------------------------------ -- Get the job status. -- ------------------------------ function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type is begin return Job.Job.Get_Status; end Get_Status; -- ------------------------------ -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. -- ------------------------------ procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type) is begin case Job.Job.Get_Status is when AWA.Jobs.Models.CANCELED | Models.FAILED | Models.TERMINATED => raise Closed_Error; when Models.SCHEDULED | Models.RUNNING => Job.Job.Set_Status (Status); end case; end Set_Status; -- ------------------------------ -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. -- ------------------------------ procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class) is begin if Job.Results_Modified then Job.Job.Set_Results (Util.Serialize.Tools.To_JSON (Job.Results)); Job.Results_Modified := False; end if; Job.Job.Save (DB); end Save; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; Sess : constant AWA.Users.Models.Session_Ref := Ctx.Get_User_Session; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Job_Create_Event.Kind); Manager.Set_Event_Queue (Msg, "job-queue"); end Set_Event; begin if Job.Job.Is_Inserted then Log.Error ("Job is already scheduled"); raise Schedule_Error with "The job is already scheduled."; end if; AWA.Jobs.Modules.Create_Event (Msg); Job.Job.Set_Create_Date (Msg.Get_Create_Date); DB.Begin_Transaction; Job.Job.Set_Name (Definition.Get_Name); Job.Job.Set_User (User); Job.Job.Set_Session (Sess); Job.Save (DB); -- Create the event Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props)); App.Do_Event_Manager (Process => Set_Event'Access); Msg.Set_User (User); Msg.Set_Session (Sess); Msg.Set_Entity_Id (Job.Job.Get_Id); Msg.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (Session => DB, Object => Job.Job.Get_Key)); Msg.Save (DB); Job.Job.Set_Event (Msg); Job.Job.Save (DB); DB.Commit; end Schedule; -- ------------------------------ -- Execute the job and save the job information in the database. -- ------------------------------ procedure Execute (Job : in out Abstract_Job_Type'Class; DB : in out ADO.Sessions.Master_Session'Class) is use type AWA.Jobs.Models.Job_Status_Type; begin -- Execute the job with an exception guard. begin Job.Execute; exception when E : others => Log.Error ("Exception when executing job {0}", Job.Job.Get_Name); Log.Error ("Exception:", E, True); Job.Job.Set_Status (Models.FAILED); end; -- If the job did not set a completion status, mark it as terminated. if Job.Job.Get_Status = Models.SCHEDULED or Job.Job.Get_Status = Models.RUNNING then Job.Job.Set_Status (Models.TERMINATED); end if; -- And save the job. DB.Begin_Transaction; Job.Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Save (DB); DB.Commit; end Execute; -- ------------------------------ -- Execute the job associated with the given event. -- ------------------------------ procedure Execute (Event : in AWA.Events.Module_Event'Class) is use AWA.Jobs.Modules; use type AWA.Modules.Module_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => Abstract_Job_Type'Class, Name => Abstract_Job_Access); Ctx : constant ASC.Service_Context_Access := ASC.Current; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; Module : constant AWA.Modules.Module_Access := App.Find_Module (AWA.Jobs.Modules.NAME); DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Job : AWA.Jobs.Models.Job_Ref; begin if Module = null then Log.Warn ("There is no Job module to execute a job"); raise Execute_Error; end if; if not (Module.all in AWA.Jobs.Modules.Job_Module'Class) then Log.Warn ("The 'job' module is not a valid module for job execution"); raise Execute_Error; end if; DB.Begin_Transaction; Job.Load (Session => DB, Id => Event.Get_Entity_Identifier); Job.Set_Start_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Set_Status (AWA.Jobs.Models.RUNNING); Job.Save (Session => DB); DB.Commit; declare Name : constant String := Job.Get_Name; begin Log.Info ("Restoring job '{0}'", Name); declare Plugin : constant Job_Module_Access := Job_Module'Class (Module.all)'Access; Factory : constant Job_Factory_Access := Plugin.Find_Factory (Name); Work : AWA.Jobs.Services.Abstract_Job_Access := null; begin if Factory /= null then Work := Factory.Create; Work.Job := Job; Work.Execute (DB); Free (Work); else Log.Error ("There is no factory to execute job '{0}'", Name); Job.Set_Status (AWA.Jobs.Models.FAILED); Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); DB.Begin_Transaction; Job.Save (Session => DB); DB.Commit; end if; end; end; end Execute; function Get_Name (Factory : in Job_Factory'Class) return String is begin return Ada.Tags.Expanded_Name (Factory'Tag); end Get_Name; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class) is begin Job.Work := Work.Work; Job.Job.Set_Name (Work.Get_Name); end Set_Work; procedure Execute (Job : in out Job_Type) is begin Job.Work (Job); end Execute; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access is begin return new Job_Type '(Ada.Finalization.Limited_Controlled with Work => Factory.Work, others => <>); end Create; -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. package body Definition is function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access is pragma Unreferenced (Factory); begin return new T; end Create; end Definition; end AWA.Jobs.Services;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.Tools; with Util.Log.Loggers; with Ada.Tags; with Ada.Calendar; with Ada.Unchecked_Deallocation; with ADO.Sessions.Entities; with AWA.Users.Models; with AWA.Events.Models; with AWA.Services.Contexts; with AWA.Jobs.Modules; with AWA.Applications; with AWA.Events.Services; with AWA.Modules; package body AWA.Jobs.Services is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services"); -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Integer) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object) is begin Job.Props.Include (Name, Value); Job.Props_Modified := True; end Set_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String is Value : constant Util.Beans.Objects.Object := Job.Get_Parameter (Name); begin return Util.Beans.Objects.To_String (Value); end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value as an integer. -- If the parameter is not defined, return the default value passed in <b>Default</b>. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String; Default : in Integer) return Integer is Pos : constant Util.Beans.Objects.Maps.Cursor := Job.Props.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then declare Value : constant Util.Beans.Objects.Object := Util.Beans.Objects.Maps.Element (Pos); begin if Util.Beans.Objects.Is_Null (Value) then return Default; else return Util.Beans.Objects.To_Integer (Value); end if; end; else return Default; end if; end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object is begin return Job.Props.Element (Name); end Get_Parameter; -- ------------------------------ -- Get the job status. -- ------------------------------ function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type is begin return Job.Job.Get_Status; end Get_Status; -- ------------------------------ -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. -- ------------------------------ procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type) is begin case Job.Job.Get_Status is when AWA.Jobs.Models.CANCELED | Models.FAILED | Models.TERMINATED => raise Closed_Error; when Models.SCHEDULED | Models.RUNNING => Job.Job.Set_Status (Status); end case; end Set_Status; -- ------------------------------ -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. -- ------------------------------ procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class) is begin if Job.Results_Modified then Job.Job.Set_Results (Util.Serialize.Tools.To_JSON (Job.Results)); Job.Results_Modified := False; end if; Job.Job.Save (DB); end Save; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; Sess : constant AWA.Users.Models.Session_Ref := Ctx.Get_User_Session; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Job_Create_Event.Kind); Manager.Set_Event_Queue (Msg, "job-queue"); end Set_Event; begin if Job.Job.Is_Inserted then Log.Error ("Job is already scheduled"); raise Schedule_Error with "The job is already scheduled."; end if; AWA.Jobs.Modules.Create_Event (Msg); Job.Job.Set_Create_Date (Msg.Get_Create_Date); DB.Begin_Transaction; Job.Job.Set_Name (Definition.Get_Name); Job.Job.Set_User (User); Job.Job.Set_Session (Sess); Job.Save (DB); -- Create the event Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props)); App.Do_Event_Manager (Process => Set_Event'Access); Msg.Set_User (User); Msg.Set_Session (Sess); Msg.Set_Entity_Id (Job.Job.Get_Id); Msg.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (Session => DB, Object => Job.Job.Get_Key)); Msg.Save (DB); Job.Job.Set_Event (Msg); Job.Job.Save (DB); DB.Commit; end Schedule; -- ------------------------------ -- Execute the job and save the job information in the database. -- ------------------------------ procedure Execute (Job : in out Abstract_Job_Type'Class; DB : in out ADO.Sessions.Master_Session'Class) is use type AWA.Jobs.Models.Job_Status_Type; begin -- Execute the job with an exception guard. begin Job.Execute; exception when E : others => Log.Error ("Exception when executing job {0}", Job.Job.Get_Name); Log.Error ("Exception:", E, True); Job.Job.Set_Status (Models.FAILED); end; -- If the job did not set a completion status, mark it as terminated. if Job.Job.Get_Status = Models.SCHEDULED or Job.Job.Get_Status = Models.RUNNING then Job.Job.Set_Status (Models.TERMINATED); end if; -- And save the job. DB.Begin_Transaction; Job.Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Save (DB); DB.Commit; end Execute; -- ------------------------------ -- Execute the job associated with the given event. -- ------------------------------ procedure Execute (Event : in AWA.Events.Module_Event'Class) is use AWA.Jobs.Modules; use type AWA.Modules.Module_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => Abstract_Job_Type'Class, Name => Abstract_Job_Access); Ctx : constant ASC.Service_Context_Access := ASC.Current; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; Module : constant AWA.Modules.Module_Access := App.Find_Module (AWA.Jobs.Modules.NAME); DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Job : AWA.Jobs.Models.Job_Ref; begin if Module = null then Log.Warn ("There is no Job module to execute a job"); raise Execute_Error; end if; if not (Module.all in AWA.Jobs.Modules.Job_Module'Class) then Log.Warn ("The 'job' module is not a valid module for job execution"); raise Execute_Error; end if; DB.Begin_Transaction; Job.Load (Session => DB, Id => Event.Get_Entity_Identifier); Job.Set_Start_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Set_Status (AWA.Jobs.Models.RUNNING); Job.Save (Session => DB); DB.Commit; declare Name : constant String := Job.Get_Name; begin Log.Info ("Restoring job '{0}'", Name); declare Plugin : constant Job_Module_Access := Job_Module'Class (Module.all)'Access; Factory : constant Job_Factory_Access := Plugin.Find_Factory (Name); Work : AWA.Jobs.Services.Abstract_Job_Access := null; begin if Factory /= null then Work := Factory.Create; Work.Job := Job; Event.Copy (Work.Props); Work.Execute (DB); Free (Work); else Log.Error ("There is no factory to execute job '{0}'", Name); Job.Set_Status (AWA.Jobs.Models.FAILED); Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); DB.Begin_Transaction; Job.Save (Session => DB); DB.Commit; end if; end; end; end Execute; function Get_Name (Factory : in Job_Factory'Class) return String is begin return Ada.Tags.Expanded_Name (Factory'Tag); end Get_Name; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class) is begin Job.Work := Work.Work; Job.Job.Set_Name (Work.Get_Name); end Set_Work; procedure Execute (Job : in out Job_Type) is begin Job.Work (Job); end Execute; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access is begin return new Job_Type '(Ada.Finalization.Limited_Controlled with Work => Factory.Work, others => <>); end Create; -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. package body Definition is function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access is pragma Unreferenced (Factory); begin return new T; end Create; end Definition; end AWA.Jobs.Services;
Copy the event properties to the job properties so that the job parameters are available
Copy the event properties to the job properties so that the job parameters are available
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
749c6bb63775f6d21c1cfbece50d891830af9e8a
awa/src/awa-users-beans.adb
awa/src/awa-users-beans.adb
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with ASF.Sessions; with ASF.Events.Actions; with ASF.Contexts.Faces; with AWA.Users.Principals; package body AWA.Users.Beans is use AWA.Users.Model; -- Action to register a user procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Email : Email_Ref; begin Email.Set_Email (Data.Email); User.Set_First_Name (Data.First_Name); User.Set_Last_Name (Data.Last_Name); User.Set_Password (Data.Password); Data.Manager.Create_User (User => User, Email => Email); Outcome := To_Unbounded_String ("success"); end Register_User; -- Action to verify the user after the registration procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Verify_User (Key => To_String (Data.Access_Key), User => User, IpAddr => "", Session => Session); Outcome := To_Unbounded_String ("success"); end Verify_User; -- Action to trigger the lost password email process. procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is begin Data.Manager.Lost_Password (Email => To_String (Data.Email)); Outcome := To_Unbounded_String ("success"); end Lost_Password; -- Action to validate the reset password key and set a new password. procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Reset_Password (Key => To_String (Data.Access_Key), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); end Reset_Password; procedure Set_Session_Principal (Data : in Authenticate_Bean; User : in AWA.Users.Model.User_Ref) is Principal : AWA.Users.Principals.Principal_Access := AWA.Users.Principals.Create (User); Ctx : ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True); Name : constant String := "User: " & User.Get_Name; begin Session.Set_Principal (Principal.all'Access); Session.Set_Attribute (Name => "user", Value => Util.Beans.Objects.To_Object (Name)); end Set_Session_Principal; -- Action to authenticate a user. procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Authenticate (Email => To_String (Data.Email), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); Data.Set_Session_Principal (User); end Authenticate_User; -- Create an authenticate bean. function Create_Authenticate_Bean (Module : in AWA.Users.Module.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : Authenticate_Bean_Access := new Authenticate_Bean; begin Object.Module := Module; Object.Manager := AWA.Users.Logic.Create_User_Manager (Module); return Object.all'Access; end Create_Authenticate_Bean; -- The code below this line could be generated automatically by an Asis tool. package Authenticate_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Authenticate_User, Name => "authenticate"); package Register_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Register_User, Name => "register"); package Verify_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Verify_User, Name => "verify"); package Lost_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Lost_Password, Name => "lostPassword"); package Reset_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Reset_Password, Name => "resetPassword"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Authenticate_Binding.Proxy'Unchecked_Access, Register_Binding.Proxy'Unchecked_Access, Verify_Binding.Proxy'Unchecked_Access, Lost_Password_Binding.Proxy'Unchecked_Access, Reset_Password_Binding.Proxy'Unchecked_Access); -- Get the value identified by the name. overriding function Get_Value (From : in Authenticate_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "password" then return Util.Beans.Objects.To_Object (From.Password); elsif Name = "key" then return Util.Beans.Objects.To_Object (From.Access_Key); 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 Authenticate_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "password" then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "key" then From.Access_Key := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Unchecked_Access; end Get_Method_Bindings; end AWA.Users.Beans;
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with ASF.Sessions; with ASF.Events.Actions; with ASF.Contexts.Faces; with AWA.Users.Principals; package body AWA.Users.Beans is use AWA.Users.Model; -- Action to register a user procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Email : Email_Ref; begin Email.Set_Email (Data.Email); User.Set_First_Name (Data.First_Name); User.Set_Last_Name (Data.Last_Name); User.Set_Password (Data.Password); Data.Manager.Create_User (User => User, Email => Email); Outcome := To_Unbounded_String ("success"); end Register_User; -- Action to verify the user after the registration procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Verify_User (Key => To_String (Data.Access_Key), User => User, IpAddr => "", Session => Session); Outcome := To_Unbounded_String ("success"); end Verify_User; -- Action to trigger the lost password email process. procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is begin Data.Manager.Lost_Password (Email => To_String (Data.Email)); Outcome := To_Unbounded_String ("success"); end Lost_Password; -- Action to validate the reset password key and set a new password. procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Reset_Password (Key => To_String (Data.Access_Key), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); end Reset_Password; procedure Set_Session_Principal (Data : in Authenticate_Bean; User : in AWA.Users.Model.User_Ref) is Principal : AWA.Users.Principals.Principal_Access := AWA.Users.Principals.Create (User); Ctx : ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True); Name : constant String := "User: " & User.Get_Name; begin Session.Set_Principal (Principal.all'Access); Session.Set_Attribute (Name => "user", Value => Util.Beans.Objects.To_Object (Name)); end Set_Session_Principal; -- Action to authenticate a user. procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Authenticate (Email => To_String (Data.Email), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); Data.Set_Session_Principal (User); end Authenticate_User; -- Create an authenticate bean. function Create_Authenticate_Bean (Module : in AWA.Users.Module.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : Authenticate_Bean_Access := new Authenticate_Bean; begin Object.Module := Module; Object.Manager := AWA.Users.Logic.Create_User_Manager (Module); return Object.all'Access; end Create_Authenticate_Bean; -- The code below this line could be generated automatically by an Asis tool. package Authenticate_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Authenticate_User, Name => "authenticate"); package Register_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Register_User, Name => "register"); package Verify_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Verify_User, Name => "verify"); package Lost_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Lost_Password, Name => "lostPassword"); package Reset_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Reset_Password, Name => "resetPassword"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Authenticate_Binding.Proxy'Access, Register_Binding.Proxy'Access, Verify_Binding.Proxy'Access, Lost_Password_Binding.Proxy'Access, Reset_Password_Binding.Proxy'Access); -- Get the value identified by the name. overriding function Get_Value (From : in Authenticate_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "password" then return Util.Beans.Objects.To_Object (From.Password); elsif Name = "key" then return Util.Beans.Objects.To_Object (From.Access_Key); 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 Authenticate_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "password" then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "key" then From.Access_Key := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; end AWA.Users.Beans;
Replace Unchecked_Access by Access since the objects are declared at package level scope
Replace Unchecked_Access by Access since the objects are declared at package level scope
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
12e6842f5186b72baf6578f4de8d1f8c5628a009
mat/src/mat-readers.ads
mat/src/mat-readers.ads
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Finalization; with System; with Util.Streams.Buffered; with MAT.Types; with MAT.Events; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access all Buffer_Type; type Message_Type is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; subtype Message is Message_Type; private type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN); type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Buffer : Util.Streams.Buffered.Buffer_Access; Size : Natural; Total : Natural; Endian : Endian_Type := LITTLE_ENDIAN; end record; end MAT.Readers;
----------------------------------------------------------------------- -- 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 Ada.Containers; -- with Ada.Finalization; with System; with Util.Streams.Buffered; -- with MAT.Types; with MAT.Events; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access all Buffer_Type; type Message_Type is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; subtype Message is Message_Type; private type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN); type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Buffer : Util.Streams.Buffered.Buffer_Access; Size : Natural; Total : Natural; Endian : Endian_Type := LITTLE_ENDIAN; end record; end MAT.Readers;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
02d75c88d257805d7af0a50f3683c07dcaead782
src/gen-commands-page.adb
src/gen-commands-page.adb
----------------------------------------------------------------------- -- gen-commands-page -- Page creation command for dynamo -- 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 Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with Util.Strings; package body Gen.Commands.Page is -- ------------------------------ -- 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); use Ada.Strings.Unbounded; function Get_Layout return String; function Get_Name return String; Dir : constant String := Generator.Get_Result_Directory & "web/"; function Get_Name return String is Name : constant String := Args.Get_Argument (1); Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos = 0 then return Name; elsif Name (Pos .. Name'Last) = ".xhtml" then return Name (Name'First .. Pos - 1); elsif Name (Pos .. Name'Last) = ".html" then return Name (Name'First .. Pos - 1); else return Name; end if; end Get_Name; function Get_Layout return String is begin if Args.Get_Count = 1 then return "layout"; end if; declare Layout : constant String := Args.Get_Argument (2); begin if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then return Layout; end if; Generator.Info ("Layout file {0} not found.", Layout); return Layout; end; end Get_Layout; begin if Args.Get_Count = 0 or Args.Get_Count > 2 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); Generator.Set_Global ("pageName", Get_Name); Generator.Set_Global ("layout", Get_Layout); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page"); 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); use Ada.Text_IO; use Ada.Directories; Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts"; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Search : Search_Type; Ent : Directory_Entry_Type; begin Put_Line ("add-page: Add a new web page to the application"); Put_Line ("Usage: add-page NAME [LAYOUT]"); New_Line; Put_Line (" The web page is an XHTML file created under the 'web' directory."); Put_Line (" The NAME can contain a directory that will be created if necessary."); Put_Line (" The new web page can be configured to use the given layout."); Put_Line (" The layout file must exist to be used. The default layout is 'layout'."); Put_Line (" You can create a new layout with 'add-layout' command."); Put_Line (" You can also write your layout by adding an XHTML file in the directory:"); Put_Line (" " & Path); if Exists (Path) then New_Line; Put_Line (" Available layouts:"); Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Layout : constant String := Base_Name (Name); begin Put_Line (" " & Layout); end; end loop; end if; New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/<name>.xhtml"); end Help; end Gen.Commands.Page;
----------------------------------------------------------------------- -- gen-commands-page -- Page creation command for dynamo -- 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 Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with Util.Strings; package body Gen.Commands.Page is -- ------------------------------ -- 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); use Ada.Strings.Unbounded; function Get_Layout return String; function Get_Name return String; Dir : constant String := Generator.Get_Result_Directory & "web/"; function Get_Name return String is Name : constant String := Args.Get_Argument (1); Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos = 0 then return Name; elsif Name (Pos .. Name'Last) = ".xhtml" then return Name (Name'First .. Pos - 1); elsif Name (Pos .. Name'Last) = ".html" then return Name (Name'First .. Pos - 1); else return Name; end if; end Get_Name; function Get_Layout return String is begin if Args.Get_Count = 1 then return "layout"; end if; declare Layout : constant String := Args.Get_Argument (2); begin if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then return Layout; end if; Generator.Info ("Layout file {0} not found.", Layout); return Layout; end; end Get_Layout; begin if Args.Get_Count = 0 or Args.Get_Count > 2 then Cmd.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); Generator.Set_Global ("pageName", Get_Name); Generator.Set_Global ("layout", Get_Layout); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page"); 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); use Ada.Text_IO; use Ada.Directories; Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts"; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Search : Search_Type; Ent : Directory_Entry_Type; begin Put_Line ("add-page: Add a new web page to the application"); Put_Line ("Usage: add-page NAME [LAYOUT]"); New_Line; Put_Line (" The web page is an XHTML file created under the 'web' directory."); Put_Line (" The NAME can contain a directory that will be created if necessary."); Put_Line (" The new web page can be configured to use the given layout."); Put_Line (" The layout file must exist to be used. The default layout is 'layout'."); Put_Line (" You can create a new layout with 'add-layout' command."); Put_Line (" You can also write your layout by adding an XHTML file in the directory:"); Put_Line (" " & Path); if Exists (Path) then New_Line; Put_Line (" Available layouts:"); Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Layout : constant String := Base_Name (Name); begin Put_Line (" " & Layout); end; end loop; end if; New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/<name>.xhtml"); end Help; end Gen.Commands.Page;
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
15410eb5d629abb237963edf7b57d1ab46ac8e2e
src/wiki-plugins.ads
src/wiki-plugins.ads
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Filters; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Plugin_Context; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; type Plugin_Factory is limited Interface; type Plugin_Factory_Access is access all Plugin_Factory'Class; -- Find a plugin knowing its name. function Find (Factory : in Plugin_Factory; Name : in String) return Wiki_Plugin_Access is abstract; type Plugin_Context is limited record Filters : Wiki.Filters.Filter_Chain; Factory : Plugin_Factory_Access; Variables : Wiki.Attributes.Attribute_List; end record; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is abstract; end Wiki.Plugins;
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Filters; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Plugin_Context; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; type Plugin_Factory is limited Interface; type Plugin_Factory_Access is access all Plugin_Factory'Class; -- Find a plugin knowing its name. function Find (Factory : in Plugin_Factory; Name : in String) return Wiki_Plugin_Access is abstract; type Plugin_Context is limited record Filters : Wiki.Filters.Filter_Chain; Factory : Plugin_Factory_Access; Variables : Wiki.Attributes.Attribute_List; Syntax : Wiki.Wiki_Syntax; end record; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is abstract; end Wiki.Plugins;
Add the wiki syntax to the Plugin_Context
Add the wiki syntax to the Plugin_Context
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d31243060e6cc8824c227461ad1e29e3a5cab516
src/yaml.ads
src/yaml.ads
private with Ada.Finalization; private with Interfaces; private with Interfaces.C; private with Interfaces.C.Pointers; private with System; package YAML is type UTF8_String is new String; type Document_Type is tagged limited private; -- Holder for a YAML document type Node_Kind is (No_Node, -- An empty node Scalar_Node, -- A scalar node Sequence_Node, -- A sequence node Mapping_Node -- A mapping node ) with Convention => C; -- Type of a node in a document type Node_Ref is private; -- Reference to a node as part of a document. Such values must not outlive -- the value for the document that owns them. No_Node_Ref : constant Node_Ref; function Root_Node (Document : Document_Type'Class) return Node_Ref; -- Return the root node of a document, or No_Node_Ref for an empty -- document. function Kind (Node : Node_Ref) return Node_Kind; -- Return the type of a node function Value (Node : Node_Ref) return UTF8_String with Pre => Kind (Node) = Scalar_Node; function Length (Node : Node_Ref) return Natural with Pre => Kind (Node) in Sequence_Node | Mapping_Node; -- Return the number of items in the Node sequence/mapping function Item (Node : Node_Ref; Index : Positive) return Node_Ref with Pre => Kind (Node) = Sequence_Node; -- Return the Index'th item in Node. Index is 1-based. type Node_Pair is record Key, Value : Node_Ref; end record; -- Key/value asssociation in a mapping node function Item (Node : Node_Ref; Index : Positive) return Node_Pair with Pre => Kind (Node) = Mapping_Node; -- Return the Index'th key/value association in Node. Index is 1-based. function Item (Node : Node_Ref; Key : UTF8_String) return Node_Ref with Pre => Kind (Node) = Mapping_Node; -- Look for Key in the Node mapping. If there is one, return the -- corresponding Value. Return No_Node_Ref otherwise. type Parser_Type is tagged limited private; -- YAML document parser type Encoding_Type is (Any_Encoding, -- Let the parser choose the encoding UTF8_Encoding, -- The default UTF-8 encoding UTF16LE_Encoding, -- The UTF-16-LE encoding with BOM UTF16BE_Encoding -- The UTF-16-BE encoding with BOM ) with Convention => C; -- Stream encoding procedure Set_Input_String (Parser : in out Parser_Type'Class; Input : String; Encoding : Encoding_Type); -- Set a string input. This maintains a copy of Input in Parser. File_Error : exception; -- Exception raised when file-related errors occurs. For instance: cannot -- open a file, cannot read a file, etc. procedure Set_Input_File (Parser : in out Parser_Type'Class; Filename : String; Encoding : Encoding_Type); -- Set a file input. This opens Filename until the parser is destroyed or -- until another Set_Input_* procedure is successfuly called. If an error -- occurs while opening the file, raise a File_Error and leave the parser -- unmodified. function Load (Parser : in out Parser_Type'Class) return Document_Type; -- Parse the input stream and produce the next YAML document. -- -- Call this function subsequently to produce a sequence of documents -- constituting the input stream. If the produced document has no root -- node, it means that the document end has been reached. -- -- TODO: error handling private subtype C_Int is Interfaces.C.int; subtype C_Index is C_Int range 0 .. C_Int'Last; subtype C_Ptr_Diff is Interfaces.C.ptrdiff_t; type C_Char_Array is array (C_Index) of Interfaces.Unsigned_8; type C_Char_Access is access all C_Char_Array; type C_Node_T; type C_Node_Access is access all C_Node_T; type C_Scalar_Style_T is (Any_Scalar_Style, Plain_Scalar_Style, Single_Quoted_Scalar_Style, Double_Quoted_Scalar_Style, Literal_Scalar_Style, Folded_Scalar_Style) with Convention => C; -- Scalar styles type C_Sequence_Style_T is (Any_Sequence_Style, Block_Sequence_Style, Flow_Sequence_Style) with Convention => C; -- Sequence styles type C_Mapping_Style_T is (Any_Mapping_Style, Block_Mapping_Style, Flow_Mapping_Style) with Convention => C; -- Mapping styles type C_Mark_T is record Index, Line, Column : Interfaces.C.size_t; end record with Convention => C_Pass_By_Copy; -- The pointer position type C_Version_Directive_T is record Major, Minor : C_Int; -- Major and minor version numbers end record with Convention => C_Pass_By_Copy; -- The version directive data type C_Version_Directive_Access is access all C_Version_Directive_T; type C_Tag_Directive_T is record Handle : C_Char_Access; -- The tag handle Prefix : C_Char_Access; -- The tag prefix end record with Convention => C_Pass_By_Copy; -- The tag directive data type C_Tag_Directive_Access is access C_Tag_Directive_T; subtype C_Node_Item_T is C_Int; type C_Node_Item_Array is array (C_Index range <>) of aliased C_Node_Item_T; package C_Node_Item_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Item_T, Element_Array => C_Node_Item_Array, Default_Terminator => -1); subtype C_Node_Item_Access is C_Node_Item_Accesses.Pointer; type C_Node_Pair_T is record Key, Value : C_Int; end record with Convention => C_Pass_By_Copy; type C_Node_Pair_Array is array (C_Index range <>) of aliased C_Node_Pair_T; package C_Node_Pair_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Pair_T, Element_Array => C_Node_Pair_Array, Default_Terminator => (-1, -1)); subtype C_Node_Pair_Access is C_Node_Pair_Accesses.Pointer; ---------------------------- -- Node structure binding -- ---------------------------- type C_Scalar_Node_Data is record Value : C_Char_Access; -- The scalar value Length : Interfaces.C.size_t; -- The length of the scalar value Style : C_Scalar_Style_T; -- The scalar style end record with Convention => C_Pass_By_Copy; type C_Sequence_Items is record Seq_Start, Seq_End, Seq_Top : C_Node_Item_Access; end record with Convention => C_Pass_By_Copy; type C_Sequence_Node_Data is record Items : C_Sequence_Items; -- The stack of sequence items Style : C_Sequence_Style_T; -- The sequence style end record with Convention => C_Pass_By_Copy; type C_Mapping_Pairs is record Map_Start, Map_End, Map_Top : C_Node_Pair_Access; end record with Convention => C_Pass_By_Copy; type C_Mapping_Node_Data is record Pairs : C_Mapping_Pairs; -- The stack of mapping pairs Style : C_Mapping_Style_T; -- The mapping style end record with Convention => C_Pass_By_Copy; type C_Node_Data (Dummy : Node_Kind := No_Node) is record case Dummy is when No_Node => null; when Scalar_Node => Scalar : C_Scalar_Node_Data; -- The scalar parameters (for Scalar_Node) when Sequence_Node => Sequence : C_Sequence_Node_Data; -- The sequence parameters (for Sequence_Node) when Mapping_Node => Mapping : C_Mapping_Node_Data; -- The mapping parameters (for Mapping_Node) end case; end record with Convention => C_Pass_By_Copy, Unchecked_Union; type C_Node_T is record Kind : Node_Kind; -- The node type Tag : C_Char_Access; -- The node tag Data : C_Node_Data; -- The node data Start_Mark, End_Mark : C_Mark_T; end record with Convention => C_Pass_By_Copy; -------------------------------- -- Document structure binding -- -------------------------------- type C_Document_Nodes is record Start_Node, End_Node, Top_Node : C_Node_T; -- Begining, end and top of the stack end record with Convention => C_Pass_By_Copy; type C_Tag_Directives is record Start_Dir, End_Dir : C_Tag_Directive_Access; -- Beginning and end of the tag directives list end record with Convention => C_Pass_By_Copy; type C_Document_T is record Nodes : C_Document_Nodes; -- The document nodes Version_Directives : C_Version_Directive_Access; -- The version directive Tag_Directives : C_Tag_Directives; -- The list of tag directives Start_Implicit, End_Implicit : C_Int; -- Is the document start/end indicator explicit? Start_Mark, End_Mark : C_Mark_T; -- Beginning and end of the document end record with Convention => C_Pass_By_Copy; -- The document structure type C_Document_Access is access all C_Document_T; ------------------------- -- High-level Wrappers -- ------------------------- type Document_Type is limited new Ada.Finalization.Limited_Controlled with record C_Doc : aliased C_Document_T; To_Delete : Boolean; end record; overriding procedure Initialize (Document : in out Document_Type); overriding procedure Finalize (Document : in out Document_Type); type Document_Access is access all Document_Type'Class; type Node_Ref is record Node : C_Node_Access; -- The referenced node Document : Document_Access; -- The document it belongs to end record; No_Node_Ref : constant Node_Ref := (null, null); type C_Parser_Access is new System.Address; type String_Access is access String; type C_File_Ptr is new System.Address; No_File_Ptr : constant C_File_Ptr := C_File_Ptr (System.Null_Address); type Parser_Type is limited new Ada.Finalization.Limited_Controlled with record C_Parser : C_Parser_Access; Input_Encoding : Encoding_Type; Input_String : String_Access; Input_File : C_File_Ptr; end record; overriding procedure Initialize (Parser : in out Parser_Type); overriding procedure Finalize (Parser : in out Parser_Type); end YAML;
private with Ada.Finalization; private with Interfaces; private with Interfaces.C; private with Interfaces.C.Pointers; private with System; package YAML is type UTF8_String is new String; type Document_Type is tagged limited private; -- Holder for a YAML document type Node_Kind is (No_Node, -- An empty node Scalar_Node, -- A scalar node Sequence_Node, -- A sequence node Mapping_Node -- A mapping node ) with Convention => C; -- Type of a node in a document type Node_Ref is private; -- Reference to a node as part of a document. Such values must not outlive -- the value for the document that owns them. No_Node_Ref : constant Node_Ref; function Root_Node (Document : Document_Type'Class) return Node_Ref; -- Return the root node of a document, or No_Node_Ref for an empty -- document. function Kind (Node : Node_Ref) return Node_Kind; -- Return the type of a node function Value (Node : Node_Ref) return UTF8_String with Pre => Kind (Node) = Scalar_Node; function Length (Node : Node_Ref) return Natural with Pre => Kind (Node) in Sequence_Node | Mapping_Node; -- Return the number of items in the Node sequence/mapping function Item (Node : Node_Ref; Index : Positive) return Node_Ref with Pre => Kind (Node) = Sequence_Node and then Index <= Length (Node); -- Return the Index'th item in Node. Index is 1-based. type Node_Pair is record Key, Value : Node_Ref; end record; -- Key/value asssociation in a mapping node function Item (Node : Node_Ref; Index : Positive) return Node_Pair with Pre => Kind (Node) = Mapping_Node and then Index <= Length (Node); -- Return the Index'th key/value association in Node. Index is 1-based. function Item (Node : Node_Ref; Key : UTF8_String) return Node_Ref with Pre => Kind (Node) = Mapping_Node; -- Look for Key in the Node mapping. If there is one, return the -- corresponding Value. Return No_Node_Ref otherwise. type Parser_Type is tagged limited private; -- YAML document parser type Encoding_Type is (Any_Encoding, -- Let the parser choose the encoding UTF8_Encoding, -- The default UTF-8 encoding UTF16LE_Encoding, -- The UTF-16-LE encoding with BOM UTF16BE_Encoding -- The UTF-16-BE encoding with BOM ) with Convention => C; -- Stream encoding procedure Set_Input_String (Parser : in out Parser_Type'Class; Input : String; Encoding : Encoding_Type); -- Set a string input. This maintains a copy of Input in Parser. File_Error : exception; -- Exception raised when file-related errors occurs. For instance: cannot -- open a file, cannot read a file, etc. procedure Set_Input_File (Parser : in out Parser_Type'Class; Filename : String; Encoding : Encoding_Type); -- Set a file input. This opens Filename until the parser is destroyed or -- until another Set_Input_* procedure is successfuly called. If an error -- occurs while opening the file, raise a File_Error and leave the parser -- unmodified. function Load (Parser : in out Parser_Type'Class) return Document_Type; -- Parse the input stream and produce the next YAML document. -- -- Call this function subsequently to produce a sequence of documents -- constituting the input stream. If the produced document has no root -- node, it means that the document end has been reached. -- -- TODO: error handling private subtype C_Int is Interfaces.C.int; subtype C_Index is C_Int range 0 .. C_Int'Last; subtype C_Ptr_Diff is Interfaces.C.ptrdiff_t; type C_Char_Array is array (C_Index) of Interfaces.Unsigned_8; type C_Char_Access is access all C_Char_Array; type C_Node_T; type C_Node_Access is access all C_Node_T; type C_Scalar_Style_T is (Any_Scalar_Style, Plain_Scalar_Style, Single_Quoted_Scalar_Style, Double_Quoted_Scalar_Style, Literal_Scalar_Style, Folded_Scalar_Style) with Convention => C; -- Scalar styles type C_Sequence_Style_T is (Any_Sequence_Style, Block_Sequence_Style, Flow_Sequence_Style) with Convention => C; -- Sequence styles type C_Mapping_Style_T is (Any_Mapping_Style, Block_Mapping_Style, Flow_Mapping_Style) with Convention => C; -- Mapping styles type C_Mark_T is record Index, Line, Column : Interfaces.C.size_t; end record with Convention => C_Pass_By_Copy; -- The pointer position type C_Version_Directive_T is record Major, Minor : C_Int; -- Major and minor version numbers end record with Convention => C_Pass_By_Copy; -- The version directive data type C_Version_Directive_Access is access all C_Version_Directive_T; type C_Tag_Directive_T is record Handle : C_Char_Access; -- The tag handle Prefix : C_Char_Access; -- The tag prefix end record with Convention => C_Pass_By_Copy; -- The tag directive data type C_Tag_Directive_Access is access C_Tag_Directive_T; subtype C_Node_Item_T is C_Int; type C_Node_Item_Array is array (C_Index range <>) of aliased C_Node_Item_T; package C_Node_Item_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Item_T, Element_Array => C_Node_Item_Array, Default_Terminator => -1); subtype C_Node_Item_Access is C_Node_Item_Accesses.Pointer; type C_Node_Pair_T is record Key, Value : C_Int; end record with Convention => C_Pass_By_Copy; type C_Node_Pair_Array is array (C_Index range <>) of aliased C_Node_Pair_T; package C_Node_Pair_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Pair_T, Element_Array => C_Node_Pair_Array, Default_Terminator => (-1, -1)); subtype C_Node_Pair_Access is C_Node_Pair_Accesses.Pointer; ---------------------------- -- Node structure binding -- ---------------------------- type C_Scalar_Node_Data is record Value : C_Char_Access; -- The scalar value Length : Interfaces.C.size_t; -- The length of the scalar value Style : C_Scalar_Style_T; -- The scalar style end record with Convention => C_Pass_By_Copy; type C_Sequence_Items is record Seq_Start, Seq_End, Seq_Top : C_Node_Item_Access; end record with Convention => C_Pass_By_Copy; type C_Sequence_Node_Data is record Items : C_Sequence_Items; -- The stack of sequence items Style : C_Sequence_Style_T; -- The sequence style end record with Convention => C_Pass_By_Copy; type C_Mapping_Pairs is record Map_Start, Map_End, Map_Top : C_Node_Pair_Access; end record with Convention => C_Pass_By_Copy; type C_Mapping_Node_Data is record Pairs : C_Mapping_Pairs; -- The stack of mapping pairs Style : C_Mapping_Style_T; -- The mapping style end record with Convention => C_Pass_By_Copy; type C_Node_Data (Dummy : Node_Kind := No_Node) is record case Dummy is when No_Node => null; when Scalar_Node => Scalar : C_Scalar_Node_Data; -- The scalar parameters (for Scalar_Node) when Sequence_Node => Sequence : C_Sequence_Node_Data; -- The sequence parameters (for Sequence_Node) when Mapping_Node => Mapping : C_Mapping_Node_Data; -- The mapping parameters (for Mapping_Node) end case; end record with Convention => C_Pass_By_Copy, Unchecked_Union; type C_Node_T is record Kind : Node_Kind; -- The node type Tag : C_Char_Access; -- The node tag Data : C_Node_Data; -- The node data Start_Mark, End_Mark : C_Mark_T; end record with Convention => C_Pass_By_Copy; -------------------------------- -- Document structure binding -- -------------------------------- type C_Document_Nodes is record Start_Node, End_Node, Top_Node : C_Node_T; -- Begining, end and top of the stack end record with Convention => C_Pass_By_Copy; type C_Tag_Directives is record Start_Dir, End_Dir : C_Tag_Directive_Access; -- Beginning and end of the tag directives list end record with Convention => C_Pass_By_Copy; type C_Document_T is record Nodes : C_Document_Nodes; -- The document nodes Version_Directives : C_Version_Directive_Access; -- The version directive Tag_Directives : C_Tag_Directives; -- The list of tag directives Start_Implicit, End_Implicit : C_Int; -- Is the document start/end indicator explicit? Start_Mark, End_Mark : C_Mark_T; -- Beginning and end of the document end record with Convention => C_Pass_By_Copy; -- The document structure type C_Document_Access is access all C_Document_T; ------------------------- -- High-level Wrappers -- ------------------------- type Document_Type is limited new Ada.Finalization.Limited_Controlled with record C_Doc : aliased C_Document_T; To_Delete : Boolean; end record; overriding procedure Initialize (Document : in out Document_Type); overriding procedure Finalize (Document : in out Document_Type); type Document_Access is access all Document_Type'Class; type Node_Ref is record Node : C_Node_Access; -- The referenced node Document : Document_Access; -- The document it belongs to end record; No_Node_Ref : constant Node_Ref := (null, null); type C_Parser_Access is new System.Address; type String_Access is access String; type C_File_Ptr is new System.Address; No_File_Ptr : constant C_File_Ptr := C_File_Ptr (System.Null_Address); type Parser_Type is limited new Ada.Finalization.Limited_Controlled with record C_Parser : C_Parser_Access; Input_Encoding : Encoding_Type; Input_String : String_Access; Input_File : C_File_Ptr; end record; overriding procedure Initialize (Parser : in out Parser_Type); overriding procedure Finalize (Parser : in out Parser_Type); end YAML;
Add Index range checks in YAML.Item preconditions
Add Index range checks in YAML.Item preconditions
Ada
mit
pmderodat/libyaml-ada,pmderodat/libyaml-ada
704ef7a8575986e6309496df24e16d334063f7f5
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; with Security.Contexts; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is begin return False; end Has_Permission; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; with Security.Contexts; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Permissions.Permission_Index; begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; end Has_Permission; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
Implement Has_Permission
Implement Has_Permission
Ada
apache-2.0
stcarrez/ada-security
d4738738d6158f59d9aa43482a9798a4d735df26
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with AWA.Blogs.Modules; with AWA.Blogs.Models; package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST); type Init_Map is array (Init_Flag) of Boolean; type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with AWA.Blogs.Modules; with AWA.Blogs.Models; with AWA.Tags.Beans; package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; POST_TAG_ATTR : constant String := "tags"; -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier; -- List of tags associated with the post. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST); type Init_Map is array (Init_Flag) of Boolean; type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); end AWA.Blogs.Beans;
Add a list of tags to the post
Add a list of tags to the post
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5ec24493fa3222636d7f3cf09881cafcf3821048
regtests/ado_harness.adb
regtests/ado_harness.adb
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- 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 ADO.Testsuite; with ADO.Drivers; with Regtests; with Util.Tests; with Util.Properties; procedure ADO_Harness is procedure Initialize (Props : in Util.Properties.Manager); procedure Harness is new Util.Tests.Harness (ADO.Testsuite.Suite, Initialize); -- ------------------------------ -- Initialization procedure: setup the database -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager) is DB : constant String := Props.Get ("test.database", "sqlite:///regtests.db"); begin ADO.Drivers.Initialize; Regtests.Initialize (DB); end Initialize; begin Harness ("ado-tests.xml"); end ADO_Harness;
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- Copyright (C) 2009, 2010, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Testsuite; with ADO.Drivers.Initializer; with Regtests; with Util.Tests; with Util.Properties; procedure ADO_Harness is procedure Initialize (Props : in Util.Properties.Manager); procedure Harness is new Util.Tests.Harness (ADO.Testsuite.Suite, Initialize); procedure Init_Drivers is new ADO.Drivers.Initializer (Util.Properties.Manager'Class, ADO.Drivers.Initialize); -- ------------------------------ -- Initialization procedure: setup the database -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager) is DB : constant String := Props.Get ("test.database", "sqlite:///regtests.db"); begin Init_Drivers (Props); Regtests.Initialize (DB); end Initialize; begin Harness ("ado-tests.xml"); end ADO_Harness;
Initialize the database drivers
Initialize the database drivers
Ada
apache-2.0
Letractively/ada-ado
03237add331b06e61a262343dcd94772313315e7
src/gen-commands-info.ads
src/gen-commands-info.ads
----------------------------------------------------------------------- -- gen-commands-info -- Collect and give information about the project -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Info is -- ------------------------------ -- Project Information Command -- ------------------------------ -- This command collects information about the project and print it. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Info;
----------------------------------------------------------------------- -- gen-commands-info -- Collect and give information about the project -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Info is -- ------------------------------ -- Project Information Command -- ------------------------------ -- This command collects information about the project and print it. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Info;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
610825b051bac557c3a83f88a9bd859a1440371a
src/babel-base-users.ads
src/babel-base-users.ads
----------------------------------------------------------------------- -- babel-base-users-- User's database for file owership identification -- 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. ----------------------------------------------------------------------- private with Ada.Finalization; private with Ada.Containers.Hashed_Maps; with Util.Strings; -- == User database == -- The <tt>Babel.Base.Users</tt> package defines a small database that maintains the -- mapping between a user or group name and the user <tt>uid_t</tt> or group <tt>gid_t</tt>. -- The mapping is obtained by using the Posix.1-2001 operations getpwnam_r (3) and -- getgrnam_r (3). The Posix operations are called once for a given name/id and they are -- stored in several hash map. A protected type is used to maintain the user and group -- mapping cache so that concurrent accesses are possible. package Babel.Base.Users is subtype Name_Access is Util.Strings.Name_Access; -- Information about a user and its group. type User_Type is record Name : Name_Access; Group : Name_Access; Uid : Uid_Type; Gid : Gid_Type; end record; NO_USER : constant User_Type; type Database is tagged limited private; type Database_Access is access all Database'Class; -- Find the UID and GID for the user that corresponds to the given name and group. function Find (From : in Database; Name : in String; Group : in String) return User_Type; -- Find the UID and GID for the user that corresponds to the given name and group. function Find (From : in Database; Name : in Uid_Type; Group : in Gid_Type) return User_Type; -- Get the user name associated with the given UID. -- Returns null if the UID was not found. function Get_Name (From : in Database; Id : in Uid_Type) return Name_Access; -- Get the UID associated with the given user name. function Get_Uid (From : in Database; Name : in String) return Uid_Type; -- Get the group name associated with the given GID. -- Returns null if the GID was not found. function Get_Group (From : in Database; Id : in Gid_Type) return Name_Access; -- Get the GID associated with the given group name. function Get_Gid (From : in Database; Name : in String) return Gid_Type; private INVALID_ID : constant Natural := Natural'Last; NO_USER : constant User_Type := User_Type'(Name => null, Group => null, Uid => Uid_Type'Last, Gid => Gid_Type'Last); function Hash (Key : in Natural) return Ada.Containers.Hash_Type; package Id_Map is new Ada.Containers.Hashed_Maps (Key_Type => Natural, Element_Type => Name_Access, Hash => Hash, Equivalent_Keys => "=", "=" => Util.Strings."="); package Name_Map is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Natural, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys, "=" => "="); -- To keep the implementation simple, the same protected type and same hash maps -- is used for the users and groups database. protected type Local_Base is -- Find in the ID map for the associated user/group name. -- If the item is not found in the map, call the <tt>Search</tt> function to resolve it. -- If the ID was not found, return a null name. procedure Find_Name (Id : in Natural; Search : not null access function (Id : in Natural) return String; Name : out Name_Access); -- Find in the name map for the corresponding ID. -- If the name was not found in the map, call the <tt>Search</tt> function to resolve it. procedure Find_Id (Name : in String; Search : not null access function (Name : in String) return Natural; Id : out Natural); procedure Clear; private Names : Name_Map.Map; Ids : Id_Map.Map; end Local_Base; type Database is limited new Ada.Finalization.Limited_Controlled with record User_Base : aliased Local_Base; Group_Base : aliased Local_Base; Users : access Local_Base; Groups : access Local_Base; end record; overriding procedure Initialize (Db : in out Database); overriding procedure Finalize (Db : in out Database); end Babel.Base.Users;
----------------------------------------------------------------------- -- babel-base-users-- User's database for file owership identification -- 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. ----------------------------------------------------------------------- private with Ada.Finalization; private with Ada.Containers.Hashed_Maps; with Util.Strings; -- == User database == -- The <tt>Babel.Base.Users</tt> package defines a small database that maintains the -- mapping between a user or group name and the user <tt>uid_t</tt> or group <tt>gid_t</tt>. -- The mapping is obtained by using the Posix.1-2001 operations getpwnam_r (3) and -- getgrnam_r (3). The Posix operations are called once for a given name/id and they are -- stored in several hash map. A protected type is used to maintain the user and group -- mapping cache so that concurrent accesses are possible. package Babel.Base.Users is subtype Name_Access is Util.Strings.Name_Access; -- Information about a user and its group. type User_Type is record Name : Name_Access; Group : Name_Access; Uid : Uid_Type; Gid : Gid_Type; end record; NO_USER : constant User_Type; type Database is tagged limited private; type Database_Access is access all Database'Class; -- Find the UID and GID for the user that corresponds to the given name and group. function Find (From : in Database; User : in String; Group : in String) return User_Type; -- Find the UID and GID for the user that corresponds to the given name and group. function Find (From : in Database; User : in Uid_Type; Group : in Gid_Type) return User_Type; -- Get the user name associated with the given UID. -- Returns null if the UID was not found. function Get_Name (From : in Database; Id : in Uid_Type) return Name_Access; -- Get the UID associated with the given user name. function Get_Uid (From : in Database; Name : in String) return Uid_Type; -- Get the group name associated with the given GID. -- Returns null if the GID was not found. function Get_Group (From : in Database; Id : in Gid_Type) return Name_Access; -- Get the GID associated with the given group name. function Get_Gid (From : in Database; Name : in String) return Gid_Type; private INVALID_ID : constant Natural := Natural'Last; NO_USER : constant User_Type := User_Type'(Name => null, Group => null, Uid => Uid_Type'Last, Gid => Gid_Type'Last); function Hash (Key : in Natural) return Ada.Containers.Hash_Type; package Id_Map is new Ada.Containers.Hashed_Maps (Key_Type => Natural, Element_Type => Name_Access, Hash => Hash, Equivalent_Keys => "=", "=" => Util.Strings."="); package Name_Map is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Natural, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys, "=" => "="); -- To keep the implementation simple, the same protected type and same hash maps -- is used for the users and groups database. protected type Local_Base is -- Find in the ID map for the associated user/group name. -- If the item is not found in the map, call the <tt>Search</tt> function to resolve it. -- If the ID was not found, return a null name. procedure Find_Name (Id : in Natural; Search : not null access function (Id : in Natural) return String; Name : out Name_Access); -- Find in the name map for the corresponding ID. -- If the name was not found in the map, call the <tt>Search</tt> function to resolve it. procedure Find_Id (Name : in String; Search : not null access function (Name : in String) return Natural; Id : out Natural; Result : out Name_Access); procedure Clear; private Names : Name_Map.Map; Ids : Id_Map.Map; end Local_Base; type Database is limited new Ada.Finalization.Limited_Controlled with record User_Base : aliased Local_Base; Group_Base : aliased Local_Base; Users : access Local_Base; Groups : access Local_Base; end record; overriding procedure Initialize (Db : in out Database); overriding procedure Finalize (Db : in out Database); end Babel.Base.Users;
Update the declaration of Find and Find_Id operations
Update the declaration of Find and Find_Id operations
Ada
apache-2.0
stcarrez/babel
bd4a9dbc7db04ed6c50dd0e8daf24c06ef1d0e8a
src/wiki-parsers-html.ads
src/wiki-parsers-html.ads
----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- -- This is a small HTML parser that is called to deal with embedded HTML in wiki text. -- The parser is intended to handle incorrect HTML and clean the result as much as possible. -- We cannot use a real XML/Sax parser (such as XML/Ada) because we must handle errors and -- backtrack from HTML parsing to wiki or raw text parsing. -- -- When parsing HTML content, we call the <tt>Start_Element</tt> or <tt>End_Element</tt> -- operations. The renderer is then able to handle the HTML tag according to its needs. private package Wiki.Parsers.Html is pragma Preelaborate; -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> procedure Parse_Element (P : in out Parser); -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. procedure Parse_Entity (P : in out Parser; Token : in Wide_Wide_Character); 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. ----------------------------------------------------------------------- -- This is a small HTML parser that is called to deal with embedded HTML in wiki text. -- The parser is intended to handle incorrect HTML and clean the result as much as possible. -- We cannot use a real XML/Sax parser (such as XML/Ada) because we must handle errors and -- backtrack from HTML parsing to wiki or raw text parsing. -- -- When parsing HTML content, we call the <tt>Start_Element</tt> or <tt>End_Element</tt> -- operations. The renderer is then able to handle the HTML tag according to its needs. private package Wiki.Parsers.Html is pragma Preelaborate; -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> procedure Parse_Element (P : in out Parser); -- 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); end Wiki.Parsers.Html;
Use the Wiki.Strings.UString type and operations
Use the Wiki.Strings.UString type and operations
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
fea459464c67d774e5105924092a524457033c90
src/base/beans/util-beans-objects-datasets.adb
src/base/beans/util-beans-objects-datasets.adb
----------------------------------------------------------------------- -- util-beans-objects-datasets -- Datasets -- Copyright (C) 2013, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Beans.Objects.Datasets is procedure Free is new Ada.Unchecked_Deallocation (Object => Object_Array, Name => Object_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Dataset_Array, Name => Dataset_Array_Access); -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : in Dataset) return Natural is begin return From.Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out Dataset; Index : in Natural) is begin From.Current_Pos := Index; From.Current.Data := From.Data (Index); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : in Dataset) return Util.Beans.Objects.Object is begin return From.Row; 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 Dataset; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); elsif Name = "rowIndex" then return Util.Beans.Objects.To_Object (From.Current_Pos); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get an iterator to iterate starting with the first element. -- ------------------------------ overriding function First (From : in Dataset) return Iterators.Proxy_Iterator_Access is Iter : constant Dataset_Iterator_Access := new Dataset_Iterator; begin Iter.Current_Pos := 1; Iter.Current.Map := From.Current.Map; if From.Count > 0 then Iter.Current.Data := From.Data (1); end if; return Iter.all'Access; end First; -- ------------------------------ -- Get an iterator to iterate starting with the last element. -- ------------------------------ overriding function Last (From : in Dataset) return Iterators.Proxy_Iterator_Access is Iter : constant Dataset_Iterator_Access := new Dataset_Iterator; begin Iter.Current_Pos := From.Count; Iter.Current.Map := From.Current.Map; if From.Count > 0 then Iter.Current.Data := From.Data (From.Count); end if; return Iter.all'Access; end Last; -- ------------------------------ -- Append a row in the dataset and call the fill procedure to populate -- the row content. -- ------------------------------ procedure Append (Into : in out Dataset; Fill : not null access procedure (Data : in out Object_Array)) is Data : constant Object_Array_Access := new Object_Array (1 .. Into.Columns); begin if Into.Data = null then Into.Data := new Dataset_Array (1 .. 10); elsif Into.Count >= Into.Data'Length then declare -- Sun's Java ArrayList use a 2/3 grow factor. -- Python's array use 8/9. Grow : constant Positive := Into.Count + (Into.Count * 2) / 3; Set : constant Dataset_Array_Access := new Dataset_Array (1 .. Grow); begin Set (Into.Data'Range) := Into.Data.all; Free (Into.Data); Into.Data := Set; end; end if; Into.Count := Into.Count + 1; Into.Data (Into.Count) := Data; Fill (Data.all); end Append; -- ------------------------------ -- Add a column to the dataset. If the position is not specified, -- the column count is incremented and the name associated with the last column. -- Raises Invalid_State exception if the dataset contains some rows, -- ------------------------------ procedure Add_Column (Into : in out Dataset; Name : in String; Pos : in Natural := 0) is Col : Positive; begin if Into.Count /= 0 then raise Invalid_State with "The dataset contains some rows."; end if; if Pos = 0 then Col := Into.Columns + 1; else Col := Pos; end if; Into.Map.Insert (Name, Col); if Into.Columns < Col then Into.Columns := Col; end if; end Add_Column; -- ------------------------------ -- Clear the content of the dataset. -- ------------------------------ procedure Clear (Set : in out Dataset) is begin for I in 1 .. Set.Count loop Free (Set.Data (I)); end loop; Set.Count := 0; Set.Current_Pos := 0; Set.Current.Data := null; end Clear; -- ------------------------------ -- 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 Row; Name : in String) return Util.Beans.Objects.Object is Pos : constant Dataset_Map.Cursor := From.Map.Find (Name); begin if From.Data /= null and then Dataset_Map.Has_Element (Pos) then return From.Data (Dataset_Map.Element (Pos)); else return Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Row; Name : in String; Value : in Util.Beans.Objects.Object) is Pos : constant Dataset_Map.Cursor := From.Map.Find (Name); begin if From.Data /= null and then Dataset_Map.Has_Element (Pos) then From.Data (Dataset_Map.Element (Pos)) := Value; end if; end Set_Value; -- ------------------------------ -- Get an iterator to iterate starting with the first element. -- ------------------------------ overriding function First (From : in Row) return Iterators.Proxy_Iterator_Access is Iter : constant Row_Iterator_Access := new Row_Iterator; begin Iter.Pos := From.Map.First; Iter.Data := From.Data; return Iter.all'Access; end First; -- ------------------------------ -- Get an iterator to iterate starting with the last element. -- ------------------------------ overriding function Last (From : in Row) return Iterators.Proxy_Iterator_Access is begin return null; end Last; -- ------------------------------ -- Initialize the dataset and the row bean instance. -- ------------------------------ overriding procedure Initialize (Set : in out Dataset) is begin Set.Row := To_Object (Value => Set.Current'Unchecked_Access, Storage => STATIC); Set.Current.Map := Set.Map'Unchecked_Access; end Initialize; -- ------------------------------ -- Release the dataset storage. -- ------------------------------ overriding procedure Finalize (Set : in out Dataset) is begin Set.Clear; Free (Set.Data); end Finalize; -- ------------------------------ -- Initialize the dataset and the row bean instance. -- ------------------------------ overriding procedure Initialize (Iter : in out Dataset_Iterator) is begin Iter.Row := To_Object (Value => Iter.Current'Unchecked_Access, Storage => STATIC); end Initialize; function Get_Dataset is new Util.Beans.Objects.Iterators.Get_Bean (Dataset, Dataset_Access); overriding function Has_Element (Iter : in Dataset_Iterator) return Boolean is List : constant Dataset_Access := Get_Dataset (Iter); begin return List /= null and then Iter.Current_Pos /= 0 and then Iter.Current_Pos <= List.Count; end Has_Element; overriding procedure Next (Iter : in out Dataset_Iterator) is List : constant Dataset_Access := Get_Dataset (Iter); begin if List /= null and then Iter.Current_Pos <= List.Count then Iter.Current_Pos := Iter.Current_Pos + 1; if Iter.Current_Pos <= List.Count then Iter.Current.Data := List.Data (Iter.Current_Pos); end if; end if; end Next; overriding procedure Previous (Iter : in out Dataset_Iterator) is List : constant Dataset_Access := Get_Dataset (Iter); begin if List /= null and then Iter.Current_Pos > 0 then Iter.Current_Pos := Iter.Current_Pos - 1; if Iter.Current_Pos > 0 then Iter.Current.Data := List.Data (Iter.Current_Pos); end if; end if; end Previous; overriding function Element (Iter : in Dataset_Iterator) return Object is begin return Iter.Row; end Element; overriding procedure Initialize (Iter : in out Row_Iterator) is begin null; end Initialize; overriding function Has_Element (Iter : in Row_Iterator) return Boolean is begin return Dataset_Map.Has_Element (Iter.Pos); end Has_Element; overriding procedure Next (Iter : in out Row_Iterator) is begin Dataset_Map.Next (Iter.Pos); end Next; overriding procedure Previous (Iter : in out Row_Iterator) is begin null; end Previous; overriding function Element (Iter : in Row_Iterator) return Object is begin return Iter.Data (Dataset_Map.Element (Iter.Pos)); end Element; overriding function Key (Iter : in Row_Iterator) return String is begin return Dataset_Map.Key (Iter.Pos); end Key; end Util.Beans.Objects.Datasets;
----------------------------------------------------------------------- -- util-beans-objects-datasets -- Datasets -- Copyright (C) 2013, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Beans.Objects.Datasets is procedure Free is new Ada.Unchecked_Deallocation (Object => Object_Array, Name => Object_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Dataset_Array, Name => Dataset_Array_Access); -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : in Dataset) return Natural is begin return From.Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out Dataset; Index : in Natural) is begin From.Current_Pos := Index; From.Current.Data := From.Data (Index); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : in Dataset) return Util.Beans.Objects.Object is begin return From.Row; 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 Dataset; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); elsif Name = "rowIndex" then return Util.Beans.Objects.To_Object (From.Current_Pos); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get an iterator to iterate starting with the first element. -- ------------------------------ overriding function First (From : in Dataset) return Iterators.Proxy_Iterator_Access is Iter : constant Dataset_Iterator_Access := new Dataset_Iterator; begin Iter.Current_Pos := 1; Iter.Current.Map := From.Current.Map; if From.Count > 0 then Iter.Current.Data := From.Data (1); end if; return Iter.all'Access; end First; -- ------------------------------ -- Get an iterator to iterate starting with the last element. -- ------------------------------ overriding function Last (From : in Dataset) return Iterators.Proxy_Iterator_Access is Iter : constant Dataset_Iterator_Access := new Dataset_Iterator; begin Iter.Current_Pos := From.Count; Iter.Current.Map := From.Current.Map; if From.Count > 0 then Iter.Current.Data := From.Data (From.Count); end if; return Iter.all'Access; end Last; -- ------------------------------ -- Append a row in the dataset and call the fill procedure to populate -- the row content. -- ------------------------------ procedure Append (Into : in out Dataset; Fill : not null access procedure (Data : in out Object_Array)) is Data : constant Object_Array_Access := new Object_Array (1 .. Into.Columns); begin if Into.Data = null then Into.Data := new Dataset_Array (1 .. 10); elsif Into.Count >= Into.Data'Length then declare -- Sun's Java ArrayList use a 2/3 grow factor. -- Python's array use 8/9. Grow : constant Positive := Into.Count + (Into.Count * 2) / 3; Set : constant Dataset_Array_Access := new Dataset_Array (1 .. Grow); begin Set (Into.Data'Range) := Into.Data.all; Free (Into.Data); Into.Data := Set; end; end if; Into.Count := Into.Count + 1; Into.Data (Into.Count) := Data; Fill (Data.all); end Append; -- ------------------------------ -- Add a column to the dataset. If the position is not specified, -- the column count is incremented and the name associated with the last column. -- Raises Invalid_State exception if the dataset contains some rows, -- ------------------------------ procedure Add_Column (Into : in out Dataset; Name : in String; Pos : in Natural := 0) is Col : Positive; begin if Into.Count /= 0 then raise Invalid_State with "The dataset contains some rows."; end if; if Pos = 0 then Col := Into.Columns + 1; else Col := Pos; end if; Into.Map.Insert (Name, Col); if Into.Columns < Col then Into.Columns := Col; end if; end Add_Column; -- ------------------------------ -- Clear the content of the dataset. -- ------------------------------ procedure Clear (Set : in out Dataset) is begin for I in 1 .. Set.Count loop Free (Set.Data (I)); end loop; Set.Count := 0; Set.Current_Pos := 0; Set.Current.Data := null; end Clear; -- ------------------------------ -- 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 Row; Name : in String) return Util.Beans.Objects.Object is Pos : constant Dataset_Map.Cursor := From.Map.Find (Name); begin if From.Data /= null and then Dataset_Map.Has_Element (Pos) then return From.Data (Dataset_Map.Element (Pos)); else return Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Row; Name : in String; Value : in Util.Beans.Objects.Object) is Pos : constant Dataset_Map.Cursor := From.Map.Find (Name); begin if From.Data /= null and then Dataset_Map.Has_Element (Pos) then From.Data (Dataset_Map.Element (Pos)) := Value; end if; end Set_Value; -- ------------------------------ -- Get an iterator to iterate starting with the first element. -- ------------------------------ overriding function First (From : in Row) return Iterators.Proxy_Iterator_Access is Iter : constant Row_Iterator_Access := new Row_Iterator; begin Iter.Pos := From.Map.First; Iter.Data := From.Data; return Iter.all'Access; end First; -- ------------------------------ -- Get an iterator to iterate starting with the last element. -- ------------------------------ overriding function Last (From : in Row) return Iterators.Proxy_Iterator_Access is pragma Unreferenced (From); begin return null; end Last; -- ------------------------------ -- Initialize the dataset and the row bean instance. -- ------------------------------ overriding procedure Initialize (Set : in out Dataset) is begin Set.Row := To_Object (Value => Set.Current'Unchecked_Access, Storage => STATIC); Set.Current.Map := Set.Map'Unchecked_Access; end Initialize; -- ------------------------------ -- Release the dataset storage. -- ------------------------------ overriding procedure Finalize (Set : in out Dataset) is begin Set.Clear; Free (Set.Data); end Finalize; -- ------------------------------ -- Initialize the dataset and the row bean instance. -- ------------------------------ overriding procedure Initialize (Iter : in out Dataset_Iterator) is begin Iter.Row := To_Object (Value => Iter.Current'Unchecked_Access, Storage => STATIC); end Initialize; function Get_Dataset is new Util.Beans.Objects.Iterators.Get_Bean (Dataset, Dataset_Access); overriding function Has_Element (Iter : in Dataset_Iterator) return Boolean is List : constant Dataset_Access := Get_Dataset (Iter); begin return List /= null and then Iter.Current_Pos /= 0 and then Iter.Current_Pos <= List.Count; end Has_Element; overriding procedure Next (Iter : in out Dataset_Iterator) is List : constant Dataset_Access := Get_Dataset (Iter); begin if List /= null and then Iter.Current_Pos <= List.Count then Iter.Current_Pos := Iter.Current_Pos + 1; if Iter.Current_Pos <= List.Count then Iter.Current.Data := List.Data (Iter.Current_Pos); end if; end if; end Next; overriding procedure Previous (Iter : in out Dataset_Iterator) is List : constant Dataset_Access := Get_Dataset (Iter); begin if List /= null and then Iter.Current_Pos > 0 then Iter.Current_Pos := Iter.Current_Pos - 1; if Iter.Current_Pos > 0 then Iter.Current.Data := List.Data (Iter.Current_Pos); end if; end if; end Previous; overriding function Element (Iter : in Dataset_Iterator) return Object is begin return Iter.Row; end Element; overriding procedure Initialize (Iter : in out Row_Iterator) is begin null; end Initialize; overriding function Has_Element (Iter : in Row_Iterator) return Boolean is begin return Dataset_Map.Has_Element (Iter.Pos); end Has_Element; overriding procedure Next (Iter : in out Row_Iterator) is begin Dataset_Map.Next (Iter.Pos); end Next; overriding procedure Previous (Iter : in out Row_Iterator) is begin null; end Previous; overriding function Element (Iter : in Row_Iterator) return Object is begin return Iter.Data (Dataset_Map.Element (Iter.Pos)); end Element; overriding function Key (Iter : in Row_Iterator) return String is begin return Dataset_Map.Key (Iter.Pos); end Key; end Util.Beans.Objects.Datasets;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3649d6443d2cb2a52ef499a0a33a2272626b4965
src/sqlite/ado-drivers-connections-sqlite.adb
src/sqlite/ado-drivers-connections-sqlite.adb
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Sessions; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Rollback; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is Result : int; begin Log.Info ("Close connection {0}", Database.Name); if Database.Server /= null then Result := Sqlite3_H.sqlite3_close_v2 (Database.Server); if Result /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot close database {0}: {1}", To_String (Database.Name), Msg); end; end if; Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release database connection"); if Database.Server /= null then Database.Close; end if; end Finalize; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is pragma Unreferenced (D); use Strings; Name : constant String := To_String (Config.Database); Filename : Strings.chars_ptr; Status : int; Handle : aliased access Sqlite3; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot open SQLite database: {0}", Msg); raise Connection_Error with "Cannot open database: " & Msg; end; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name : in String; Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := Util.Properties.To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name : in String; Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item); begin if Util.Strings.Index (Name, '.') = 0 then Log.Info ("Configure database with {0}", SQL); ADO.Statements.Sqlite.Execute (Database.Server, SQL); end if; exception when SQL_Error => null; end Configure; begin Database.Server := Handle; Database.Name := Config.Database; Result := Ref.Create (Database.all'Access); -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Properties.Iterate (Process => Configure'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with Util.Processes.Tools; with ADO.Sessions; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Rollback; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is Result : int; begin Log.Info ("Close connection {0}", Database.Name); if Database.Server /= null then Result := Sqlite3_H.sqlite3_close_v2 (Database.Server); if Result /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot close database {0}: {1}", To_String (Database.Name), Msg); end; end if; Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release database connection"); if Database.Server /= null then Database.Close; end if; end Finalize; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; -- ------------------------------ -- Create the database and initialize it with the schema SQL file. -- ------------------------------ procedure Create_Database (Database : in Database_Connection; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is pragma Unreferenced (Database); Status : Integer; Database_Path : constant String := Config.Get_Database; Command : constant String := "sqlite3 --batch --init " & Schema_Path & " " & Database_Path; begin Log.Info ("Creating SQLite database {0}", Database_Path); Messages.Clear; Util.Processes.Tools.Execute (Command, Messages, Status); if Status = 0 then Log.Info ("Database schema created successfully."); elsif Status = 255 then Messages.Append ("Command not found: " & Command); Log.Error ("Command not found: {0}", Command); else Log.Error ("Command {0} failed with exit code {1}", Command, Util.Strings.Image (Status)); end if; end Create_Database; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is pragma Unreferenced (D); use Strings; Name : constant String := Config.Get_Database; Filename : Strings.chars_ptr; Status : int; Handle : aliased access Sqlite3; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot open SQLite database: {0}", Msg); raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg; end; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name : in String; Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := Util.Properties.To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name : in String; Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item); begin if Util.Strings.Index (Name, '.') = 0 then Log.Info ("Configure database with {0}", SQL); ADO.Statements.Sqlite.Execute (Database.Server, SQL); end if; exception when SQL_Error => null; end Configure; begin Database.Server := Handle; Database.Name := To_Unbounded_String (Config.Get_Database); Result := Ref.Create (Database.all'Access); -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Iterate (Process => Configure'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; end ADO.Drivers.Connections.Sqlite;
Implement Create_Database procedure Update Create_Connection procedure to use the ADO.Configs operations
Implement Create_Database procedure Update Create_Connection procedure to use the ADO.Configs operations
Ada
apache-2.0
stcarrez/ada-ado
6d474313bcc1a8fd4d70236260fef225d623061c
src/babel-strategies-default.adb
src/babel-strategies-default.adb
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- 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. ----------------------------------------------------------------------- pragma Ada_2012; with Babel.Files.Signatures; package body Babel.Strategies.Default is -- Returns true if there is a directory that must be processed by the current strategy. overriding function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean is begin return not Strategy.Queue.Directories.Is_Empty; end Has_Directory; -- Get the next directory that must be processed by the strategy. overriding function Peek_Directory (Strategy : in out Default_Strategy_Type) return String is Last : constant String := Strategy.Queue.Directories.Last_Element; begin Strategy.Queue.Directories.Delete_Last; return Last; end Peek_Directory; overriding procedure Execute (Strategy : in out Default_Strategy_Type) is Content : Babel.Files.Buffers.Buffer_Access := Strategy.Allocate_Buffer; File : Babel.Files.File; begin Strategy.Queue.Queue.Dequeue (File, 1.0); Strategy.Read_File (File, Content); Babel.Files.Signatures.Sha1 (Content.all, File.SHA1); if Babel.Files.Is_Modified (File) then Strategy.Backup_File (File, Content); else Strategy.Release_Buffer (Content); end if; exception when others => Strategy.Release_Buffer (Content); raise; end Execute; overriding procedure Add_File (Into : in out Default_Strategy_Type; Path : in String; Element : in Babel.Files.File) is begin Into.Queue.Add_File (Path, Element); end Add_File; overriding procedure Add_Directory (Into : in out Default_Strategy_Type; Path : in String; Name : in String) is begin Into.Queue.Add_Directory (Path, Name); end Add_Directory; end Babel.Strategies.Default;
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- 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. ----------------------------------------------------------------------- pragma Ada_2012; with Babel.Files.Signatures; with Util.Encoders.SHA1; package body Babel.Strategies.Default is -- Returns true if there is a directory that must be processed by the current strategy. overriding function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean is begin return not Strategy.Queue.Directories.Is_Empty; end Has_Directory; -- Get the next directory that must be processed by the strategy. overriding function Peek_Directory (Strategy : in out Default_Strategy_Type) return String is Last : constant String := Strategy.Queue.Directories.Last_Element; begin Strategy.Queue.Directories.Delete_Last; return Last; end Peek_Directory; overriding procedure Execute (Strategy : in out Default_Strategy_Type) is Content : Babel.Files.Buffers.Buffer_Access := Strategy.Allocate_Buffer; File : Babel.Files.File_Type; SHA1 : Util.Encoders.SHA1.Hash_Array; begin Strategy.Queue.Queue.Dequeue (File, 1.0); Strategy.Read_File (File, Content); Babel.Files.Signatures.Sha1 (Content.all, SHA1); Babel.Files.Set_Signature (File, SHA1); if Babel.Files.Is_Modified (File) then Strategy.Backup_File (File, Content); else Strategy.Release_Buffer (Content); end if; exception when others => Strategy.Release_Buffer (Content); raise; end Execute; overriding procedure Add_File (Into : in out Default_Strategy_Type; Path : in String; Element : in Babel.Files.File) is begin Into.Queue.Add_File (Path, Element); end Add_File; overriding procedure Add_Directory (Into : in out Default_Strategy_Type; Path : in String; Name : in String) is begin Into.Queue.Add_Directory (Path, Name); end Add_Directory; end Babel.Strategies.Default;
Use the new File_Type and the Set_Signature procedure to setup the computed SHA1
Use the new File_Type and the Set_Signature procedure to setup the computed SHA1
Ada
apache-2.0
stcarrez/babel
3e13b453318d4570a9becf724b50e01f90f34443
tests/natools-s_expressions-printers-tests.adb
tests/natools-s_expressions-printers-tests.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, 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.Test_Tools; package body Natools.S_Expressions.Printers.Tests is procedure All_Tests (Report : in out NT.Reporter'Class) is begin Canonical_Test (Report); end All_Tests; procedure Canonical_Test (Report : in out NT.Reporter'Class) is Name : constant String := "Canonical encoding"; begin declare Stream : aliased Test_Tools.Memory_Stream; Printer : Canonical (Stream'Access); begin Stream.Set_Expected (To_Atom ("3:The(5:quick((5:brown3:fox)()))" & "(5:jumps)9:over3:the()4:lazy0:3:dog")); Printer.Append_Atom (To_Atom ("The")); Printer.Open_List; Printer.Append_Atom (To_Atom ("quick")); Printer.Open_List; Printer.Open_List; Printer.Append_Atom (To_Atom ("brown")); Printer.Append_Atom (To_Atom ("fox")); Printer.Close_List; Printer.Open_List; Printer.Close_List; Printer.Close_List; Printer.Close_List; Printer.Open_List; Printer.Append_Atom (To_Atom ("jumps")); Printer.Close_List; Printer.Append_Atom (To_Atom ("over3:the")); Printer.Open_List; Printer.Close_List; Printer.Append_Atom (To_Atom ("lazy")); Printer.Append_Atom (Null_Atom); Printer.Append_Atom (To_Atom ("dog")); if Stream.Has_Mismatch or else Stream.Unread_Expected /= Null_Atom then Report.Item (Name, NT.Fail); Report.Info ("Mismatch at position" & Count'Image (Stream.Mismatch_Index)); Report.Info ("Left to expect: """ & To_String (Stream.Unread_Expected) & '"'); Report.Info ("Written data: """ & To_String (Stream.Get_Data) & '"'); else Report.Item (Name, NT.Success); end if; end; exception when Error : others => Report.Report_Exception (Name, Error); end Canonical_Test; end Natools.S_Expressions.Printers.Tests;
------------------------------------------------------------------------------ -- Copyright (c) 2014-2015, 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.Test_Tools; package body Natools.S_Expressions.Printers.Tests is procedure All_Tests (Report : in out NT.Reporter'Class) is begin Canonical_Test (Report); end All_Tests; procedure Canonical_Test (Report : in out NT.Reporter'Class) is Name : constant String := "Canonical encoding"; begin declare Stream : aliased Test_Tools.Memory_Stream; Printer : Canonical (Stream'Access); begin Stream.Set_Expected (To_Atom ("3:The(5:quick((5:brown3:fox)()))" & "(5:jumps)9:over3:the()4:lazy0:3:dog")); Printer.Append_String ("The"); Printer.Open_List; Printer.Append_String ("quick"); Printer.Open_List; Printer.Open_List; Printer.Append_String ("brown"); Printer.Append_String ("fox"); Printer.Close_List; Printer.Open_List; Printer.Close_List; Printer.Close_List; Printer.Close_List; Printer.Open_List; Printer.Append_String ("jumps"); Printer.Close_List; Printer.Append_String ("over3:the"); Printer.Open_List; Printer.Close_List; Printer.Append_String ("lazy"); Printer.Append_Atom (Null_Atom); Printer.Append_String ("dog"); if Stream.Has_Mismatch or else Stream.Unread_Expected /= Null_Atom then Report.Item (Name, NT.Fail); Report.Info ("Mismatch at position" & Count'Image (Stream.Mismatch_Index)); Report.Info ("Left to expect: """ & To_String (Stream.Unread_Expected) & '"'); Report.Info ("Written data: """ & To_String (Stream.Get_Data) & '"'); else Report.Item (Name, NT.Success); end if; end; exception when Error : others => Report.Report_Exception (Name, Error); end Canonical_Test; end Natools.S_Expressions.Printers.Tests;
use the new Append_String procedure to keep full ocoverage
s_expressions-printers-tests: use the new Append_String procedure to keep full ocoverage
Ada
isc
faelys/natools
8a0fe1b1fadd15c605a8aa05803bb233d1cbedce
src/atlas-microblog-beans.adb
src/atlas-microblog-beans.adb
----------------------------------------------------------------------- -- atlas-microblog-beans -- Beans for module microblog -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ADO.Queries; with ASF.Events.Faces.Actions; with AWA.Events.Action_Method; package body Atlas.Microblog.Beans is -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Post (Bean : in out Microblog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Create (Bean.Post); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("post-response"); end Post; -- ------------------------------ -- Post a message when some event is received. -- ------------------------------ procedure Post (Bean : in out Microblog_Bean; Event : in AWA.Events.Module_Event'Class) is begin Bean.Module.Create (Bean.Post); end Post; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Microblog_Bean, Method => Post, Name => "post"); package Event_Action_Binding is new AWA.Events.Action_Method.Bind (Bean => Microblog_Bean, Method => Post, Name => "post_event"); Microblog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Event_Action_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Microblog_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Post.Is_Null then return Util.Beans.Objects.Null_Object; else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Microblog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "message" then From.Post.Set_Message (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Microblog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Microblog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Microblog_Bean bean instance. -- ------------------------------ function Create_Microblog_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Microblog_Bean_Access := new Microblog_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Microblog_Bean; -- ------------------------------ -- Create the a bean to display the list of microblog posts. -- ------------------------------ function Create_List_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use Models; Result : constant List_Info_List_Bean_Access := new List_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (Atlas.Microblog.Models.Query_List); Atlas.Microblog.Models.List (Result.all, Session, Query); return Result.all'Access; end Create_List_Bean; end Atlas.Microblog.Beans;
----------------------------------------------------------------------- -- atlas-microblog-beans -- Beans for module microblog -- Copyright (C) 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 ADO.Sessions; with ADO.Queries; with ASF.Events.Faces.Actions; with AWA.Events.Action_Method; package body Atlas.Microblog.Beans is -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Post (Bean : in out Microblog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Create (Bean.Post); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("post-response"); end Post; -- ------------------------------ -- Post a message when some event is received. -- ------------------------------ procedure Post (Bean : in out Microblog_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Event); begin Bean.Module.Create (Bean.Post); end Post; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Microblog_Bean, Method => Post, Name => "post"); package Event_Action_Binding is new AWA.Events.Action_Method.Bind (Bean => Microblog_Bean, Method => Post, Name => "post_event"); Microblog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Event_Action_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Microblog_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Post.Is_Null then return Util.Beans.Objects.Null_Object; else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Microblog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "message" then From.Post.Set_Message (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Microblog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Microblog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Microblog_Bean bean instance. -- ------------------------------ function Create_Microblog_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Microblog_Bean_Access := new Microblog_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Microblog_Bean; -- ------------------------------ -- Create the a bean to display the list of microblog posts. -- ------------------------------ function Create_List_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use Models; Result : constant List_Info_List_Bean_Access := new List_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (Atlas.Microblog.Models.Query_List); Atlas.Microblog.Models.List (Result.all, Session, Query); return Result.all'Access; end Create_List_Bean; end Atlas.Microblog.Beans;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/atlas
31a2c5f86bbc7973182d603ef96bf07eb60dd0a6
regtests/ado-schemas-tests.adb
regtests/ado-schemas-tests.adb
----------------------------------------------------------------------- -- schemas Tests -- Test loading of database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Test_Caller; with Util.Strings.Vectors; with Util.Strings.Transforms; with ADO.Parameters; with ADO.Schemas.Databases; with ADO.Sessions.Sources; with ADO.Schemas.Entities; with Regtests; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; function To_Lower_Case (S : in String) return String renames Util.Strings.Transforms.To_Lower_Case; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database", Test_Create_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare -- T1 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.USER_TABLE'Access); -- T2 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access); T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); begin -- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value"); -- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value"); T.Assert (T4 /= T5, "Two distinct tables have different entity types"); T.Assert (T4 > 0, "T1.Id must be positive"); T.Assert (T5 > 0, "T2.Id must be positive"); -- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids"); -- -- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4), -- "Invalid entity type for allocate_table"); -- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5), -- "Invalid entity type for user_table"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; declare P : ADO.Parameters.Parameter := ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0, Len => 0, Value_Len => 0, Position => 0, Name => ""); begin P := C.Expand ("something"); T.Assert (False, "Expand did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (Is_Primary (C), "Column must be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); T.Assert (not Is_Primary (C), "Column must not be a primary key"); Assert_Equals (T, 255, Get_Size (C), "Column has invalid size"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 21, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 10, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 10, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; -- ------------------------------ -- Test the creation of database. -- ------------------------------ procedure Test_Create_Schema (T : in out Test) is use ADO.Sessions.Sources; Msg : Util.Strings.Vectors.Vector; Cfg : Data_Source := Data_Source (Regtests.Get_Controller); Driver : constant String := Cfg.Get_Driver; Database : constant String := Cfg.Get_Database; Path : constant String := "db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql"; pragma Unreferenced (Msg); begin if Driver = "sqlite" then if Ada.Directories.Exists (Database & ".test") then Ada.Directories.Delete_File (Database & ".test"); end if; Cfg.Set_Database (Database & ".test"); ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); T.Assert (Ada.Directories.Exists (Database & ".test"), "The sqlite database was not created"); else ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); end if; end Test_Create_Schema; end ADO.Schemas.Tests;
----------------------------------------------------------------------- -- ado-schemas-tests -- Test loading of database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Test_Caller; with Util.Strings.Vectors; with Util.Strings.Transforms; with ADO.Parameters; with ADO.Schemas.Databases; with ADO.Sessions.Sources; with ADO.Sessions.Entities; with ADO.Schemas.Entities; with Regtests; with Regtests.Audits.Model; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; function To_Lower_Case (S : in String) return String renames Util.Strings.Transforms.To_Lower_Case; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database", Test_Create_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T1 : constant ADO.Entity_Type := Sessions.Entities.Find_Entity_Type (Session => S, Table => Regtests.Audits.Model.AUDIT_TABLE); T2 : constant ADO.Entity_Type := Sessions.Entities.Find_Entity_Type (Session => S, Table => Regtests.Audits.Model.EMAIL_TABLE); T3 : constant ADO.Entity_Type := Sessions.Entities.Find_Entity_Type (Session => S, Name => "audit_property"); begin T.Assert (T1 > 0, "T1 must be positive"); T.Assert (T2 > 0, "T2 must be positive"); T.Assert (T3 > 0, "T3 must be positive"); T.Assert (T4 > 0, "T4 must be positive"); T.Assert (T5 > 0, "T5 must be positive"); T.Assert (T1 /= T2, "Two distinct tables have different entity types (T1, T2)"); T.Assert (T2 /= T3, "Two distinct tables have different entity types (T2, T3)"); T.Assert (T3 /= T4, "Two distinct tables have different entity types (T3, T4)"); T.Assert (T4 /= T5, "Two distinct tables have different entity types (T4, T5)"); T.Assert (T5 /= T1, "Two distinct tables have different entity types (T5, T1)"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; declare P : ADO.Parameters.Parameter := ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0, Len => 0, Value_Len => 0, Position => 0, Name => ""); begin P := C.Expand ("something"); T.Assert (False, "Expand did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (Is_Primary (C), "Column must be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); T.Assert (not Is_Primary (C), "Column must not be a primary key"); Assert_Equals (T, 255, Get_Size (C), "Column has invalid size"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 21, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 10, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 10, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; -- ------------------------------ -- Test the creation of database. -- ------------------------------ procedure Test_Create_Schema (T : in out Test) is use ADO.Sessions.Sources; Msg : Util.Strings.Vectors.Vector; Cfg : Data_Source := Data_Source (Regtests.Get_Controller); Driver : constant String := Cfg.Get_Driver; Database : constant String := Cfg.Get_Database; Path : constant String := "db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql"; pragma Unreferenced (Msg); begin if Driver = "sqlite" then if Ada.Directories.Exists (Database & ".test") then Ada.Directories.Delete_File (Database & ".test"); end if; Cfg.Set_Database (Database & ".test"); ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); T.Assert (Ada.Directories.Exists (Database & ".test"), "The sqlite database was not created"); else ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); end if; end Test_Create_Schema; end ADO.Schemas.Tests;
Add several tests to check ADO.Sessions.Entities.Find_Entity_Type operations
Add several tests to check ADO.Sessions.Entities.Find_Entity_Type operations
Ada
apache-2.0
stcarrez/ada-ado
cbd30beef76f1a887632b61a6bff2e1c061c3481
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Parsers.Wiki_Syntax_Type); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Nodes.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Engine : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Engine : in out Wiki_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Engine : in out Wiki_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Engine : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Nodes.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Open_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Parsers.Wiki_Syntax_Type); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Nodes.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in WString; Attrs : in Attributes.Attribute_List_Type); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Link : in WString; Attrs : in Attributes.Attribute_List_Type); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in WString; Attrs : in Attributes.Attribute_List_Type); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Engine : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Nodes.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Open_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
Rename Add_Link, Add_Image, Add_Quote into Render_Link, Render_Image, Render_Quote (update the prototypes for the new implementation)
Rename Add_Link, Add_Image, Add_Quote into Render_Link, Render_Image, Render_Quote (update the prototypes for the new implementation)
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
c10b8b4f09b6c04aa90d152f521ae433714a0da9
awa/plugins/awa-storages/src/awa-storages.ads
awa/plugins/awa-storages/src/awa-storages.ads
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with ADO; -- = Storages Module = -- The `Storages` module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Simple Storage Service. -- -- == Creating a storage == -- A data in the storage is represented by a `Storage_Ref` instance. The data itself -- can be physically stored in a file system (`FILE` mode), in the database (`DATABASE` -- mode) or on a remote server (`URL` mode). To put a file in the storage space, first create -- the storage object instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses this information -- to save the data in a file, in the database or in a remote service (in the future). -- To save a file in the store, we can use the `Save` operation of the storage service. -- It will read the file and put in in the corresponding persistent store (the database -- in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File, -- Storage => AWA.Storages.Models.DATABASE); -- -- Upon successful completion, the storage instance `Data` will be allocated a unique -- identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been designed -- to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able to read -- the file. If the storage mode of the data is `FILE`, the path of the file on -- the storage file system is used. For other storage modes, the file is saved -- in a temporary file. In that case the `Store_Local` database table is used -- to track such locally saved data. -- -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream connection is -- the most efficient mechanism. -- -- == Local file == -- To access the data by using a local file, we must define a local storage reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier. When loading locally we -- also indicate whether the file will be read or written. A file that is in `READ` mode -- can be shared by several tasks or processes. A file that is in `WRITE` mode will have -- a specific copy for the caller. An optional expiration parameter indicate when the -- local file representation can expire. -- -- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- @include awa-storages-modules.ads -- @include awa-storages-services.ads -- -- == Ada Beans == -- @include-bean storages.xml -- @include-bean storage-list.xml -- @include-bean folder-queries.xml -- @include-bean storage-queries.xml -- -- @include awa-storages-servlets.ads -- -- == Queries == -- @include-query storage-list.xml -- @include-query folder-queries.xml -- @include-query storage-queries.xml -- -- == Data model == -- [images/awa_storage_model.png] -- package AWA.Storages is type Storage_Type is (DATABASE, FILE, URL, CACHE, TMP); type Storage_File (Storage : Storage_Type) is tagged limited private; -- Get the path to get access to the file. function Get_Path (File : in Storage_File) return String; -- Set the file path for the FILE, URL, CACHE or TMP storage. procedure Set (File : in out Storage_File; Path : in String); -- Set the file database storage identifier. procedure Set (File : in out Storage_File; Workspace : in ADO.Identifier; Store : in ADO.Identifier); private type Storage_File (Storage : Storage_Type) is limited new Ada.Finalization.Limited_Controlled with record case Storage is when DATABASE => Workspace : ADO.Identifier; Store : ADO.Identifier; when FILE | URL | CACHE | TMP => Path : Ada.Strings.Unbounded.Unbounded_String; end case; end record; overriding procedure Finalize (File : in out Storage_File); end AWA.Storages;
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with ADO; -- = Storages Module = -- The `Storages` module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Simple Storage Service. -- -- == Creating a storage == -- A data in the storage is represented by a `Storage_Ref` instance. The data itself -- can be physically stored in a file system (`FILE` mode), in the database (`DATABASE` -- mode) or on a remote server (`URL` mode). To put a file in the storage space, first create -- the storage object instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses this information -- to save the data in a file, in the database or in a remote service (in the future). -- To save a file in the store, we can use the `Save` operation of the storage service. -- It will read the file and put in in the corresponding persistent store (the database -- in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File, -- Storage => AWA.Storages.Models.DATABASE); -- -- Upon successful completion, the storage instance `Data` will be allocated a unique -- identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been designed -- to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able to read -- the file. If the storage mode of the data is `FILE`, the path of the file on -- the storage file system is used. For other storage modes, the file is saved -- in a temporary file. In that case the `Store_Local` database table is used -- to track such locally saved data. -- -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream connection is -- the most efficient mechanism. -- -- == Local file == -- To access the data by using a local file, we must define a local storage reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier. When loading locally we -- also indicate whether the file will be read or written. A file that is in `READ` mode -- can be shared by several tasks or processes. A file that is in `WRITE` mode will have -- a specific copy for the caller. An optional expiration parameter indicate when the -- local file representation can expire. -- -- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- @include awa-storages-modules.ads -- @include awa-storages-services.ads -- -- == Ada Beans == -- @include-bean storages.xml -- @include-bean storage-list.xml -- @include-bean folder-queries.xml -- @include-bean storage-queries.xml -- -- @include awa-storages-servlets.ads -- -- == Queries == -- @include-query storage-list.xml -- @include-query folder-queries.xml -- @include-query storage-queries.xml -- -- == Data model == -- [images/awa_storages_model.png] -- package AWA.Storages is type Storage_Type is (DATABASE, FILE, URL, CACHE, TMP); type Storage_File (Storage : Storage_Type) is tagged limited private; -- Get the path to get access to the file. function Get_Path (File : in Storage_File) return String; -- Set the file path for the FILE, URL, CACHE or TMP storage. procedure Set (File : in out Storage_File; Path : in String); -- Set the file database storage identifier. procedure Set (File : in out Storage_File; Workspace : in ADO.Identifier; Store : in ADO.Identifier); private type Storage_File (Storage : Storage_Type) is limited new Ada.Finalization.Limited_Controlled with record case Storage is when DATABASE => Workspace : ADO.Identifier; Store : ADO.Identifier; when FILE | URL | CACHE | TMP => Path : Ada.Strings.Unbounded.Unbounded_String; end case; end record; overriding procedure Finalize (File : in out Storage_File); end AWA.Storages;
Fix the data model image link
Fix the data model image link
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b90e493398f8a4f0c73deab21392e574a2e26abf
asfunit/asf-tests.adb
asfunit/asf-tests.adb
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- 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 GNAT.Regpat; with Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Util.Files; with ASF.Streams; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Servlets.Measures; with ASF.Responses; with ASF.Responses.Tools; with ASF.Filters.Dump; with ASF.Contexts.Faces; with EL.Variables.Default; package body ASF.Tests is use Ada.Strings.Unbounded; use Util.Tests; CONTEXT_PATH : constant String := "/asfunit"; Server : access ASF.Server.Container; App : ASF.Applications.Main.Application_Access := null; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; -- Save the response headers and content in a file procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response); -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class) is use type ASF.Applications.Main.Application_Access; C : ASF.Applications.Config; begin if Application /= null then App := Application; else App := new ASF.Applications.Main.Application; end if; Server := new ASF.Server.Container; Server.Register_Application (CONTEXT_PATH, App.all'Access); C.Copy (Props); App.Initialize (C, Factory); App.Register ("layoutMsg", "layout"); App.Set_Global ("contextPath", CONTEXT_PATH); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Access); App.Add_Servlet (Name => "files", Server => Files'Access); App.Add_Servlet (Name => "ajax", Server => Ajax'Access); App.Add_Servlet (Name => "measures", Server => Measures'Access); App.Add_Filter (Name => "dump", Filter => Dump'Access); App.Add_Filter (Name => "measures", Filter => ASF.Filters.Filter'Class (Measures)'Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.properties"); App.Add_Mapping (Name => "files", Pattern => "*.xhtml"); App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*"); App.Add_Mapping (Name => "measures", Pattern => "stats.xml"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*"); end Initialize; -- ------------------------------ -- Get the server -- ------------------------------ function Get_Server return access ASF.Server.Container is begin return Server; end Get_Server; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return ASF.Applications.Main.Application_Access is begin return App; end Get_Application; -- ------------------------------ -- Save the response headers and content in a file -- ------------------------------ procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response) is use ASF.Responses; Info : constant String := Tools.To_String (Reply => Response, Html => False, Print_Headers => True); Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Content : Unbounded_String; Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Response.Read_Content (Content); Stream.Write (Content); Insert (Content, 1, Info); Util.Files.Write_File (Result_Path & "/" & Name, Content); end Save_Response; -- ------------------------------ -- Simulate a raw request. The URI and method must have been set on the Request object. -- ------------------------------ procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response) is begin -- For the purpose of writing tests, clear the buffer before invoking the service. Response.Clear; Server.Service (Request => Request, Response => Response); end Do_Req; -- ------------------------------ -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "GET"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Get; -- ------------------------------ -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "POST"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Post; -- ------------------------------ -- Check that the response body contains the string -- ------------------------------ procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Index (Content, Value) > 0, Message => Message & ": value '" & Value & "' not found", Source => Source, Line => Line); end Assert_Contains; -- ------------------------------ -- Check that the response body matches the regular expression -- ------------------------------ procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is use GNAT.Regpat; Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; Regexp : constant Pattern_Matcher := Compile (Expression => Pattern, Flags => Multiple_Lines); begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, Status, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Match (Regexp, To_String (Content)), Message => Message & ": does not match '" & Pattern & "'", Source => Source, Line => Line); end Assert_Matches; -- ------------------------------ -- Check that the response body is a redirect to the given URI. -- ------------------------------ procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is begin Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status, "Invalid response", Source, Line); Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"), Message & ": missing Location", Source, Line); end Assert_Redirect; -- ------------------------------ -- Cleanup the test instance. -- ------------------------------ overriding procedure Tear_Down (T : in out EL_Test) is procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class, EL.Contexts.Default.Default_Context_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class, EL.Variables.Variable_Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class, EL.Contexts.Default.Default_ELResolver_Access); begin ASF.Contexts.Faces.Restore (null); Free (T.ELContext); Free (T.Variables); Free (T.Root_Resolver); end Tear_Down; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out EL_Test) is begin T.ELContext := new EL.Contexts.Default.Default_Context; T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver; T.Variables := new EL.Variables.Default.Default_Variable_Mapper; T.ELContext.Set_Resolver (T.Root_Resolver.all'Access); T.ELContext.Set_Variable_Mapper (T.Variables.all'Access); end Set_Up; end ASF.Tests;
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- 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 GNAT.Regpat; with Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Util.Files; with ASF.Streams; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Servlets.Measures; with ASF.Responses; with ASF.Responses.Tools; with ASF.Filters.Dump; with ASF.Contexts.Faces; with EL.Variables.Default; package body ASF.Tests is use Ada.Strings.Unbounded; use Util.Tests; CONTEXT_PATH : constant String := "/asfunit"; Server : access ASF.Server.Container; App : ASF.Applications.Main.Application_Access := null; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; -- Save the response headers and content in a file procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response); -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class) is use type ASF.Applications.Main.Application_Access; C : ASF.Applications.Config; begin if Application /= null then App := Application; else App := new ASF.Applications.Main.Application; end if; Server := new ASF.Server.Container; Server.Register_Application (CONTEXT_PATH, App.all'Access); C.Copy (Props); App.Initialize (C, Factory); App.Register ("layoutMsg", "layout"); App.Set_Global ("contextPath", CONTEXT_PATH); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Access); App.Add_Servlet (Name => "files", Server => Files'Access); App.Add_Servlet (Name => "ajax", Server => Ajax'Access); App.Add_Servlet (Name => "measures", Server => Measures'Access); App.Add_Filter (Name => "dump", Filter => Dump'Access); App.Add_Filter (Name => "measures", Filter => ASF.Filters.Filter'Class (Measures)'Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.properties"); App.Add_Mapping (Name => "files", Pattern => "*.xhtml"); App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*"); App.Add_Mapping (Name => "measures", Pattern => "stats.xml"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*"); end Initialize; -- ------------------------------ -- Get the server -- ------------------------------ function Get_Server return access ASF.Server.Container is begin return Server; end Get_Server; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return ASF.Applications.Main.Application_Access is begin return App; end Get_Application; -- ------------------------------ -- Save the response headers and content in a file -- ------------------------------ procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response) is use ASF.Responses; Info : constant String := Tools.To_String (Reply => Response, Html => False, Print_Headers => True); Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Content : Unbounded_String; Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Response.Read_Content (Content); Stream.Write (Content); Insert (Content, 1, Info); Util.Files.Write_File (Result_Path & "/" & Name, Content); end Save_Response; -- ------------------------------ -- Simulate a raw request. The URI and method must have been set on the Request object. -- ------------------------------ procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response) is begin -- For the purpose of writing tests, clear the buffer before invoking the service. Response.Clear; Server.Service (Request => Request, Response => Response); end Do_Req; -- ------------------------------ -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "GET"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Get; -- ------------------------------ -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "POST"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Post; -- ------------------------------ -- Check that the response body contains the string -- ------------------------------ procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Index (Content, Value) > 0, Message => Message & ": value '" & Value & "' not found", Source => Source, Line => Line); end Assert_Contains; -- ------------------------------ -- Check that the response body matches the regular expression -- ------------------------------ procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is use GNAT.Regpat; Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; Regexp : constant Pattern_Matcher := Compile (Expression => Pattern, Flags => Multiple_Lines); begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, Status, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Match (Regexp, To_String (Content)), Message => Message & ": does not match '" & Pattern & "'", Source => Source, Line => Line); end Assert_Matches; -- ------------------------------ -- Check that the response contains the given header. -- ------------------------------ procedure Assert_Header (T : in Util.Tests.Test'Class; Header : in String; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is begin T.Assert (Condition => Reply.Contains_Header (Header), Message => Message & ": missing header '" & Header & "'", Source => Source, Line => Line); Assert_Equals (T, Value, Reply.Get_Header (Header), Message, Source, Line); end Assert_Header; -- ------------------------------ -- Check that the response body is a redirect to the given URI. -- ------------------------------ procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is begin Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status, "Invalid response", Source, Line); Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"), Message & ": missing Location", Source, Line); end Assert_Redirect; -- ------------------------------ -- Cleanup the test instance. -- ------------------------------ overriding procedure Tear_Down (T : in out EL_Test) is procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class, EL.Contexts.Default.Default_Context_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class, EL.Variables.Variable_Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class, EL.Contexts.Default.Default_ELResolver_Access); begin ASF.Contexts.Faces.Restore (null); Free (T.ELContext); Free (T.Variables); Free (T.Root_Resolver); end Tear_Down; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out EL_Test) is begin T.ELContext := new EL.Contexts.Default.Default_Context; T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver; T.Variables := new EL.Variables.Default.Default_Variable_Mapper; T.ELContext.Set_Resolver (T.Root_Resolver.all'Access); T.ELContext.Set_Variable_Mapper (T.Variables.all'Access); end Set_Up; end ASF.Tests;
Implement the Assert_Header procedure
Implement the Assert_Header procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
629c41f8d9308c4b0727e12af5690d43a4a6a2ad
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); 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 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;
Declare the Create_Wiki_Content procedure
Declare the Create_Wiki_Content procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3ef15d269935f2d96c17d1ca522fa3877fcf8a05
mat/src/mat-consoles.ads
mat/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT, F_MODE, F_FRAME_ID, F_RANGE_ADDR, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_PID_INFO, N_DURATION, N_PATH_INFO); type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the address range and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT, F_MODE, F_FRAME_ID, F_RANGE_ADDR, F_FRAME_ADDR); type Notice_Type is (N_HELP, 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); 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;
Add N_EVENT_ID notice
Add N_EVENT_ID notice
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8d06e5affc7351079a7e8a598f3b250432e128a6
awa/plugins/awa-images/src/awa-images-beans.adb
awa/plugins/awa-images/src/awa-images-beans.adb
----------------------------------------------------------------------- -- awa-images-beans -- Image Ada Beans -- 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 ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Modules; package body AWA.Images.Beans is -- ------------------------------ -- Load the list of images associated with the current folder. -- ------------------------------ overriding procedure Load_Files (Storage : in Image_List_Bean) is use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (AWA.Storages.Beans.INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Images.Models.Query_Image_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Images.Models.List (Storage.Image_List_Bean.all, Session, Query); Storage.Flags (AWA.Storages.Beans.INIT_FILE_LIST) := True; end Load_Files; overriding function Get_Value (List : in Image_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "images" then return Util.Beans.Objects.To_Object (Value => List.Image_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then -- if not List.Init_Flags (INIT_FOLDER) then -- Load_Folder (List); -- end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Image_List_Bean bean instance. -- ------------------------------ function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); Object : constant Image_List_Bean_Access := new Image_List_Bean; begin Object.Module := AWA.Storages.Modules.Get_Storage_Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Image_List_Bean := Object.Image_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Image_List_Bean; end AWA.Images.Beans;
----------------------------------------------------------------------- -- awa-images-beans -- Image Ada Beans -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Modules; package body AWA.Images.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Load the list of images associated with the current folder. -- ------------------------------ overriding procedure Load_Files (Storage : in Image_List_Bean) is use AWA.Services; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (AWA.Storages.Beans.INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Images.Models.Query_Image_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Images.Models.List (Storage.Image_List_Bean.all, Session, Query); Storage.Flags (AWA.Storages.Beans.INIT_FILE_LIST) := True; end Load_Files; overriding function Get_Value (List : in Image_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "images" then return Util.Beans.Objects.To_Object (Value => List.Image_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then -- if not List.Init_Flags (INIT_FOLDER) then -- Load_Folder (List); -- end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Image_List_Bean bean instance. -- ------------------------------ function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); Object : constant Image_List_Bean_Access := new Image_List_Bean; begin Object.Module := AWA.Storages.Modules.Get_Storage_Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Image_List_Bean := Object.Image_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Image_List_Bean; overriding procedure Load (Into : in out Image_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; use type Ada.Containers.Count_Type; use type Ada.Strings.Unbounded.Unbounded_String; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the list of versions associated with the wiki page. Query.Set_Query (AWA.Images.Models.Query_Image_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); Into.Load (Session, Query); end Load; -- Create the Image_Bean bean instance. function Create_Image_Bean (Module : in AWA.Images.Modules.Image_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Image_Bean_Access := new Image_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Image_Bean; end AWA.Images.Beans;
Implement the Load and Create_Image_Bean operation
Implement the Load and Create_Image_Bean operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e6bb60e77a133a428e4849afb527438330b3a7b9
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Documents; with Wiki.Attributes; with Wiki.Writers; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Wiki_Renderer; Writer : in Writers.Writer_Type_Access; Format : in Parsers.Wiki_Syntax_Type); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Wiki_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Wiki_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. overriding procedure Add_List_Item (Document : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Wiki_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Wiki_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Attribute_List_Type); overriding procedure End_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Wiki_Renderer); -- Set the text style format. procedure Set_Format (Document : in out Wiki_Renderer; Format : in Documents.Format_Map); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Bold_Start, Bold_End, Italic_Start, Italic_End, Underline_Start, Underline_End, Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Documents.Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Document : in out Wiki_Renderer); procedure Close_Paragraph (Document : in out Wiki_Renderer); procedure Open_Paragraph (Document : in out Wiki_Renderer); procedure Start_Keep_Content (Document : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Documents.Document_Reader with record Writer : Writers.Writer_Type_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Documents.Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Documents.Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Documents; with Wiki.Attributes; with Wiki.Writers; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Wiki_Renderer; Writer : in Writers.Writer_Type_Access; Format : in Parsers.Wiki_Syntax_Type); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Wiki_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Wiki_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. overriding procedure Add_List_Item (Document : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Wiki_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Wiki_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Attribute_List_Type); overriding procedure End_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Wiki_Renderer); -- Set the text style format. procedure Set_Format (Document : in out Wiki_Renderer; Format : in Documents.Format_Map); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Documents.Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Document : in out Wiki_Renderer); procedure Close_Paragraph (Document : in out Wiki_Renderer); procedure Open_Paragraph (Document : in out Wiki_Renderer); procedure Start_Keep_Content (Document : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Documents.Document_Reader with record Writer : Writers.Writer_Type_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Documents.Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Documents.Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
Remove Bold_Start, Bold_End, Italic_Start, Italic_End definition
Remove Bold_Start, Bold_End, Italic_Start, Italic_End definition
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
a684aa1d7bdf9063000cbaf3e172d767464cec0e
tools/druss-commands.adb
tools/druss-commands.adb
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Util.Strings; with Util.Log.Loggers; with Readline; with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; with Druss.Commands.Devices; with Druss.Commands.Ping; package body Druss.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands"); function Uptime_Image (Value : in Natural) return String; procedure Quit (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; Device_Commands : aliased Druss.Commands.Devices.Command_Type; Ping_Commands : aliased Druss.Commands.Ping.Command_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type) is pragma Unreferenced (Command); begin if Args.Get_Count < Arg_Pos then Context.Console.Notice (N_USAGE, "Missing argument for command"); Druss.Commands.Driver.Usage (Args); end if; declare procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type); Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-d] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -d Debug execution mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); Driver.Add_Command ("devices", Device_Commands'Access); Driver.Add_Command ("ping", Ping_Commands'Access); end Initialize; -- ------------------------------ -- Quit the interactive loop. -- ------------------------------ procedure Quit (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name, Args, Context); begin raise Stop_Interactive; end Quit; -- ------------------------------ -- Enter in the interactive main loop waiting for user commands and executing them. -- ------------------------------ procedure Interactive (Context : in out Context_Type) is Args : Util.Commands.String_Argument_List (Max_Length => 1000, Max_Args => 100); begin Log.Debug ("Entering in interactive mode"); Driver.Add_Command (Name => "quit", Handler => Quit'Access); loop declare Line : constant String := Readline.Get_Line ("druss>"); begin Log.Debug ("Execute: {0}", Line); Args.Initialize (Line); Driver.Execute (Args.Get_Command_Name, Args, Context); exception when Stop_Interactive => Log.Debug ("Leaving interactive mode"); exit; when others => Context.Console.Notice (N_INFO, "Command failed"); end; end loop; exception when Ada.IO_Exceptions.End_Error => Log.Debug ("End_Error exception received"); end Interactive; -- ------------------------------ -- Print the bbox API status. -- ------------------------------ procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "2" then Console.Print_Field (Field, "OK"); elsif Value = "-1" then Console.Print_Field (Field, "KO"); elsif Value = "1" then Console.Print_Field (Field, "Starting"); elsif Value = "0" then Console.Print_Field (Field, "Stopped"); else Console.Print_Field (Field, "?"); end if; end Print_Status; -- ------------------------------ -- Print a ON/OFF status. -- ------------------------------ procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "1" then Console.Print_Field (Field, "ON"); elsif Value = "0" then Console.Print_Field (Field, "OFF"); else Console.Print_Field (Field, ""); end if; end Print_On_Off; function Uptime_Image (Value : in Natural) return String is D : constant Natural := Value / 86400; R : constant Natural := Value mod 86400; H : constant Natural := R / 3600; M : constant Natural := (R mod 3600) / 60; S : constant Natural := (R mod 3600) mod 60; begin if D > 0 then return Util.Strings.Image (D) & "d" & (if H > 0 then Natural'Image (H) & "h" else "") & (if M > 0 then Natural'Image (M) & "m" else ""); elsif H > 0 then return Util.Strings.Image (H) & "h" & (if M > 0 then Natural'Image (M) & "m" else ""); else return Util.Strings.Image (M) & "m" & Natural'Image (S) & "s"; end if; end Uptime_Image; -- ------------------------------ -- Print a uptime. -- ------------------------------ procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "" then Console.Print_Field (Field, Value); else Console.Print_Field (Field, Uptime_Image (Natural'Value (Value))); end if; exception when others => Console.Print_Field (Field, Value); end Print_Uptime; -- ------------------------------ -- Print a performance measure in us or ms. -- ------------------------------ procedure Print_Perf (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is use Commands.Consoles; begin if Value = "" then Console.Print_Field (Field, Value); elsif Value'Length <= 3 then Console.Print_Field (Field, Value & " us", J_RIGHT); elsif Value'Length <= 6 then Console.Print_Field (Field, Value (Value'First .. Value'Last - 3) & "." & Value (Value'Last - 2 .. Value'Last) & " ms", J_RIGHT); else Console.Print_Field (Field, Value (Value'First .. Value'Last - 6) & "." & Value (Value'Last - 5 .. Value'Last - 3) & " s", J_RIGHT); end if; end Print_Perf; end Druss.Commands;
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Util.Strings; with Util.Log.Loggers; with Readline; with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; with Druss.Commands.Devices; with Druss.Commands.Ping; package body Druss.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands"); function Uptime_Image (Value : in Natural) return String; procedure Quit (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; Device_Commands : aliased Druss.Commands.Devices.Command_Type; Ping_Commands : aliased Druss.Commands.Ping.Command_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type) is pragma Unreferenced (Command); begin if Args.Get_Count < Arg_Pos then Context.Console.Notice (N_USAGE, "Missing argument for command"); Druss.Commands.Driver.Usage (Args); end if; declare procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type); Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-d] [-i] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -d Debug execution mode" & ASCII.LF & " -i Enter the interactive mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); Driver.Add_Command ("devices", Device_Commands'Access); Driver.Add_Command ("ping", Ping_Commands'Access); end Initialize; -- ------------------------------ -- Quit the interactive loop. -- ------------------------------ procedure Quit (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name, Args, Context); begin raise Stop_Interactive; end Quit; -- ------------------------------ -- Enter in the interactive main loop waiting for user commands and executing them. -- ------------------------------ procedure Interactive (Context : in out Context_Type) is Args : Util.Commands.String_Argument_List (Max_Length => 1000, Max_Args => 100); begin Log.Debug ("Entering in interactive mode"); Driver.Add_Command (Name => "quit", Handler => Quit'Access); loop declare Line : constant String := Readline.Get_Line ("druss>"); begin Log.Debug ("Execute: {0}", Line); Args.Initialize (Line); Driver.Execute (Args.Get_Command_Name, Args, Context); exception when Stop_Interactive => Log.Debug ("Leaving interactive mode"); exit; when others => Context.Console.Notice (N_INFO, "Command failed"); end; end loop; exception when Ada.IO_Exceptions.End_Error => Log.Debug ("End_Error exception received"); end Interactive; -- ------------------------------ -- Print the bbox API status. -- ------------------------------ procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "2" then Console.Print_Field (Field, "OK"); elsif Value = "-1" then Console.Print_Field (Field, "KO"); elsif Value = "1" then Console.Print_Field (Field, "Starting"); elsif Value = "0" then Console.Print_Field (Field, "Stopped"); else Console.Print_Field (Field, "?"); end if; end Print_Status; -- ------------------------------ -- Print a ON/OFF status. -- ------------------------------ procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "1" then Console.Print_Field (Field, "ON"); elsif Value = "0" then Console.Print_Field (Field, "OFF"); else Console.Print_Field (Field, ""); end if; end Print_On_Off; function Uptime_Image (Value : in Natural) return String is D : constant Natural := Value / 86400; R : constant Natural := Value mod 86400; H : constant Natural := R / 3600; M : constant Natural := (R mod 3600) / 60; S : constant Natural := (R mod 3600) mod 60; begin if D > 0 then return Util.Strings.Image (D) & "d" & (if H > 0 then Natural'Image (H) & "h" else "") & (if M > 0 then Natural'Image (M) & "m" else ""); elsif H > 0 then return Util.Strings.Image (H) & "h" & (if M > 0 then Natural'Image (M) & "m" else ""); else return Util.Strings.Image (M) & "m" & Natural'Image (S) & "s"; end if; end Uptime_Image; -- ------------------------------ -- Print a uptime. -- ------------------------------ procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "" then Console.Print_Field (Field, Value); else Console.Print_Field (Field, Uptime_Image (Natural'Value (Value))); end if; exception when others => Console.Print_Field (Field, Value); end Print_Uptime; -- ------------------------------ -- Print a performance measure in us or ms. -- ------------------------------ procedure Print_Perf (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is use Commands.Consoles; begin if Value = "" then Console.Print_Field (Field, Value); elsif Value'Length <= 3 then Console.Print_Field (Field, Value & " us", J_RIGHT); elsif Value'Length <= 6 then Console.Print_Field (Field, Value (Value'First .. Value'Last - 3) & "." & Value (Value'Last - 2 .. Value'Last) & " ms", J_RIGHT); else Console.Print_Field (Field, Value (Value'First .. Value'Last - 6) & "." & Value (Value'Last - 5 .. Value'Last - 3) & " s", J_RIGHT); end if; end Print_Perf; end Druss.Commands;
Add the -i option to the usage
Add the -i option to the usage
Ada
apache-2.0
stcarrez/bbox-ada-api
2260ad13fce4902e7b411051c2e1115a3c39de3c
tools/druss-commands.adb
tools/druss-commands.adb
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; package body Druss.Commands is Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type) is begin if Args.Get_Count < Arg_Pos + 1 then Druss.Commands.Driver.Usage (Args); end if; declare Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); end Initialize; end Druss.Commands;
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; package body Druss.Commands is Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type) is begin if Args.Get_Count < Arg_Pos + 1 then Druss.Commands.Driver.Usage (Args); end if; declare Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); end Initialize; -- ------------------------------ -- Print the bbox API status. -- ------------------------------ procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "2" then Console.Print_Field (Field, "OK"); elsif Value = "-1" then Console.Print_Field (Field, "KO"); elsif Value = "1" then Console.Print_Field (Field, "Starting"); elsif Value = "0" then Console.Print_Field (Field, "Stopped"); else Console.Print_Field (Field, "?"); end if; end Print_Status; end Druss.Commands;
Implement the Print_Status operation
Implement the Print_Status operation
Ada
apache-2.0
stcarrez/bbox-ada-api
f3c9f1dcbea561b396dffae3a221c71fd9e072a3
src/security-oauth-clients.adb
src/security-oauth-clients.adb
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Numerics.Discrete_Random; with Interfaces; with Ada.Streams; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Encoders.HMAC.SHA1; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package body Security.OAuth.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); protected type Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array); private -- Random number generator used for ID generation. Random : Id_Random.Generator; -- Number of 32-bit random numbers used for the ID generation. Id_Size : Ada.Streams.Stream_Element_Offset := 8; end Random; protected body Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is use Ada.Streams; use Interfaces; begin -- Generate the random sequence. for I in 0 .. Id_Size - 1 loop declare Value : constant Unsigned_32 := Id_Random.Random (Random); begin Into (4 * I) := Stream_Element (Value and 16#0FF#); Into (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Into (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Into (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; end Generate; end Random; -- ------------------------------ -- Returns true if the given role is stored in the user principal. -- ------------------------------ function Has_Role (User : in Access_Token; Role : in Permissions.Role_Type) return Boolean is pragma Unreferenced (User, Role); begin return False; end Has_Role; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Set the application identifier used by the OAuth authorization server -- to identify the application (for example, the App ID in Facebook). -- ------------------------------ procedure Set_Application_Identifier (App : in out Application; Client : in String) is use Ada.Strings.Unbounded; begin App.Client_Id := To_Unbounded_String (Client); App.Protect := App.Client_Id & App.Callback; end Set_Application_Identifier; -- ------------------------------ -- Set the application secret defined in the OAuth authorization server -- for the application (for example, the App Secret in Facebook). -- ------------------------------ procedure Set_Application_Secret (App : in out Application; Secret : in String) is begin App.Secret := Ada.Strings.Unbounded.To_Unbounded_String (Secret); App.Key := App.Secret; end Set_Application_Secret; -- ------------------------------ -- Set the redirection callback that will be used to redirect the user -- back to the application after the OAuth authorization is finished. -- ------------------------------ procedure Set_Application_Callback (App : in out Application; URI : in String) is use Ada.Strings.Unbounded; begin App.Callback := To_Unbounded_String (URI); App.Protect := App.Client_Id & App.Callback; end Set_Application_Callback; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Protect); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Key), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Scope & "=" & Scope & "&" & Security.OAuth.State & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.Grant_Type & "=authorization_code" & "&" & Security.OAuth.Code & "=" & Code & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Client_Secret & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1}", URI, Natural'Image (Response.Get_Status)); return null; end if; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain;" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), Expires); else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin return new Access_Token '(Len => Token'Length, Access_Id => Token); end Create_Access_Token; end Security.OAuth.Clients;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Numerics.Discrete_Random; with Interfaces; with Ada.Streams; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Encoders.HMAC.SHA1; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package body Security.OAuth.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); protected type Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array); private -- Random number generator used for ID generation. Random : Id_Random.Generator; -- Number of 32-bit random numbers used for the ID generation. Id_Size : Ada.Streams.Stream_Element_Offset := 8; end Random; protected body Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is use Ada.Streams; use Interfaces; begin -- Generate the random sequence. for I in 0 .. Id_Size - 1 loop declare Value : constant Unsigned_32 := Id_Random.Random (Random); begin Into (4 * I) := Stream_Element (Value and 16#0FF#); Into (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Into (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Into (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; end Generate; end Random; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Set the application identifier used by the OAuth authorization server -- to identify the application (for example, the App ID in Facebook). -- ------------------------------ procedure Set_Application_Identifier (App : in out Application; Client : in String) is use Ada.Strings.Unbounded; begin App.Client_Id := To_Unbounded_String (Client); App.Protect := App.Client_Id & App.Callback; end Set_Application_Identifier; -- ------------------------------ -- Set the application secret defined in the OAuth authorization server -- for the application (for example, the App Secret in Facebook). -- ------------------------------ procedure Set_Application_Secret (App : in out Application; Secret : in String) is begin App.Secret := Ada.Strings.Unbounded.To_Unbounded_String (Secret); App.Key := App.Secret; end Set_Application_Secret; -- ------------------------------ -- Set the redirection callback that will be used to redirect the user -- back to the application after the OAuth authorization is finished. -- ------------------------------ procedure Set_Application_Callback (App : in out Application; URI : in String) is use Ada.Strings.Unbounded; begin App.Callback := To_Unbounded_String (URI); App.Protect := App.Client_Id & App.Callback; end Set_Application_Callback; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Protect); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Key), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Scope & "=" & Scope & "&" & Security.OAuth.State & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.Grant_Type & "=authorization_code" & "&" & Security.OAuth.Code & "=" & Code & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Client_Secret & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1}", URI, Natural'Image (Response.Get_Status)); return null; end if; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain;" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), Expires); else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin return new Access_Token '(Len => Token'Length, Access_Id => Token); end Create_Access_Token; end Security.OAuth.Clients;
Remove the Has_Role operation
Remove the Has_Role operation
Ada
apache-2.0
Letractively/ada-security
ce28af03ae858261398668e02bc6b11e9e8d3664
src/security-policies-urls.ads
src/security-policies-urls.ads
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. -- -- === Policy creation === -- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL. -- -- URI : constant String := ...; -- Perm : constant Policies.URLs.URI_Permission (1, URI'Length) -- := URI_Permission '(1, Len => URI'Length, URI => URI); -- Result : Boolean; -- -- Having the security context, we can check the permission: -- -- Context.Has_Permission (Perm, Result); -- package Security.Policies.Urls is NAME : constant String := "URL-Policy"; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Id : Permissions.Permission_Index; Len : Natural) is new Permissions.Permission (Id) with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; end record; end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. -- -- === Policy creation === -- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL. -- -- URI : constant String := ...; -- Perm : constant Policies.URLs.URI_Permission (1, URI'Length) -- := URI_Permission '(1, Len => URI'Length, URI => URI); -- Result : Boolean; -- -- Having the security context, we can check the permission: -- -- Context.Has_Permission (Perm, Result); -- package Security.Policies.Urls is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; end record; end Security.Policies.Urls;
Define and use the URL permission for the URL_Permission type
Define and use the URL permission for the URL_Permission type
Ada
apache-2.0
stcarrez/ada-security
83d341e05dbf10e430b0592d3239a0b407b0e364
mat/src/mat-targets.adb
mat/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Targets is -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is begin MAT.Memory.Targets.Initialize (Memory => Target.Memory, Reader => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Process : out Target_Process_Type_Access) is begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Target.Processes.Insert (Pid, Process); end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Targets is -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Process; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is begin MAT.Memory.Targets.Initialize (Memory => Target.Memory, Reader => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Process : out Target_Process_Type_Access) is begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Target.Processes.Insert (Pid, Process); end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; end MAT.Targets;
Implement the Process function
Implement the Process function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
19143b41ecefe1db1fa658d46c5c35772c40b8c6
src/util-strings-maps.ads
src/util-strings-maps.ads
----------------------------------------------------------------------- -- Util-strings-maps -- Map of strings -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; -- The <b>Util.Strings.Maps</b> package provides an instantiation -- of a hashed map with Strings. package Util.Strings.Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => String, Hash => Ada.Strings.Hash, Equivalent_Keys => "=");
----------------------------------------------------------------------- -- util-strings-maps -- Map of strings -- Copyright (C) 2010, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; -- The <b>Util.Strings.Maps</b> package provides an instantiation -- of a hashed map with Strings. package Util.Strings.Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => String, Hash => Ada.Strings.Hash, Equivalent_Keys => "=");
Update the header
Update the header
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
02ed95ee48095d3c3ff21ca59c64d0d294f16042
src/asf-routes-servlets.adb
src/asf-routes-servlets.adb
----------------------------------------------------------------------- -- asf-routes -- Request routing -- 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.Unchecked_Deallocation; package body ASF.Routes.Servlets is use type ASF.Filters.Filter_Access; use type ASF.Filters.Filter_List_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Filters.Filter_List, Name => ASF.Filters.Filter_List_Access); -- Get the servlet to call for the route. function Get_Servlet (Route : in Servlet_Route_Type) return ASF.Servlets.Servlet_Access is begin return Route.Servlet; end Get_Servlet; -- ------------------------------ -- Append the filter to the filter list defined by the mapping node. -- ------------------------------ procedure Append_Filter (Route : in out Servlet_Route_Type; Filter : in ASF.Filters.Filter_Access) is List : ASF.Filters.Filter_List_Access; begin -- Filters are executed through the <b>Filter_Chain.Do_Filter</b> method -- starting from the last position to the first. To append a filter, -- it must be inserted as first position of the list. if Route.Filters = null then List := new ASF.Filters.Filter_List (1 .. 1); else -- Check that the filter is not already executed. for I in Route.Filters'Range loop if Route.Filters (I) = Filter then return; end if; end loop; List := new ASF.Filters.Filter_List (1 .. Route.Filters'Last + 1); List (2 .. List'Last) := Route.Filters.all; Free (Route.Filters); end if; List (List'First) := Filter; Route.Filters := List; end Append_Filter; -- Release the storage held by the route. overriding procedure Finalize (Route : in out Servlet_Route_Type) is begin Free (Route.Filters); end Finalize; end ASF.Routes.Servlets;
----------------------------------------------------------------------- -- asf-routes -- Request routing -- 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.Unchecked_Deallocation; package body ASF.Routes.Servlets is use type ASF.Filters.Filter_Access; use type ASF.Filters.Filter_List_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Filters.Filter_List, Name => ASF.Filters.Filter_List_Access); -- ------------------------------ -- Get the servlet to call for the route. -- ------------------------------ function Get_Servlet (Route : in Servlet_Route_Type) return ASF.Servlets.Servlet_Access is begin return Route.Servlet; end Get_Servlet; -- ------------------------------ -- Append the filter to the filter list defined by the mapping node. -- ------------------------------ procedure Append_Filter (Route : in out Servlet_Route_Type; Filter : in ASF.Filters.Filter_Access) is List : ASF.Filters.Filter_List_Access; begin -- Filters are executed through the <b>Filter_Chain.Do_Filter</b> method -- starting from the last position to the first. To append a filter, -- it must be inserted as first position of the list. if Route.Filters = null then List := new ASF.Filters.Filter_List (1 .. 1); else -- Check that the filter is not already executed. for I in Route.Filters'Range loop if Route.Filters (I) = Filter then return; end if; end loop; List := new ASF.Filters.Filter_List (1 .. Route.Filters'Last + 1); List (2 .. List'Last) := Route.Filters.all; Free (Route.Filters); end if; List (List'First) := Filter; Route.Filters := List; end Append_Filter; -- ------------------------------ -- Release the storage held by the route. -- ------------------------------ overriding procedure Finalize (Route : in out Servlet_Route_Type) is begin Free (Route.Filters); end Finalize; end ASF.Routes.Servlets;
Update style
Update style
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
27f754c4052cb1afef62b7330dd139badbe5c5bf
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; -- Set the driver description printed in the usage. procedure Set_Description (Driver : in out Driver_Type; Description : 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; end record; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; 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; -- 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;
Declare the Set_Usage procedure
Declare the Set_Usage procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
59d5e1ebf16b4b379d2fdcb6cb6fbe04b73bd68e
src/base/beans/util-beans-objects-iterators.ads
src/base/beans/util-beans-objects-iterators.ads
----------------------------------------------------------------------- -- util-beans-objects-iterators -- Iterators for objects -- 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 Ada.Finalization; with Ada.Iterator_Interfaces; -- == Object iterator == -- Iterators are provided by the `Util.Beans.Objects.Iterators` package. -- The iterator instance is created by using either the `First` or `Last` -- function on the object to iterate. -- -- with Util.Beans.Objects.Iterators; -- ... -- Iter : Util.Beans.Objects.Iterators.Iterator -- := Util.Beans.Objects.Iterators.First (Object); -- -- The iterator is used in conjunction with its `Has_Element` function -- and either its `Next` or `Previous` procedure. The current element -- is obtained by using the `Element` function. When the object being -- iterated is a map, a key can be associated with the element and -- is obtained by the `Key` function. -- -- while Util.Beans.Objects.Iterators.Has_Element (Iter) loop -- declare -- Item : Object := Util.Beans.Objects.Iterators.Element (Iter); -- Key : String := Util.Beans.Objects.Iterators.Key (Iter); -- begin -- ... -- Util.Beans.Objects.Iterators.Next (Iter); -- end; -- end loop; -- package Util.Beans.Objects.Iterators is type Iterator is tagged private; -- Returns True if the iterator provides a key for each element. function Has_Key (Iter : in Iterator) return Boolean; -- Returns True if the iterator has an element. function Has_Element (Iter : in Iterator) return Boolean; -- Returns the current iterator element or Null_Object if it is empty. function Element (Iter : in Iterator) return Object; -- Returns the key associated with the current element. function Key (Iter : in Iterator) return String; -- Move the iterator to the next element. procedure Next (Iter : in out Iterator); -- Move the iterator to the previous element. procedure Previous (Iter : in out Iterator); -- Create an iterator to iterate from the first element. function First (Item : in Object) return Iterator; -- Create an iterator to iterate from the last element. function Last (Item : in Object) return Iterator; package Object_Iterator_Interfaces is new Ada.Iterator_Interfaces (Iterator, Has_Element); function Iterate (Item : in Object) return Object_Iterator_Interfaces.Forward_Iterator'Class; -- ------------------------------ -- Proxy_Iterator -- ------------------------------ -- The `Proxy_Iterator` is the base type for the implementation of an iterator. -- An instance is created by the `Iterator_Bean` interface. -- The `Porxy_Map_Iterator` extends the iterator to provide access to -- the key when the iterator gives access to the elements of a map. type Proxy_Iterator is abstract new Ada.Finalization.Limited_Controlled with private; type Proxy_Iterator_Access is access all Proxy_Iterator'Class; overriding procedure Finalize (Proxy : in out Proxy_Iterator); function Has_Element (Iter : in Proxy_Iterator) return Boolean is abstract; procedure Next (Iter : in out Proxy_Iterator) is abstract; procedure Previous (Iter : in out Proxy_Iterator) is abstract; function Element (Iter : in Proxy_Iterator) return Object is abstract; type Proxy_Map_Iterator is abstract new Proxy_Iterator with private; type Proxy_Map_Iterator_Access is access all Proxy_Map_Iterator'Class; function Key (Iter : in Proxy_Map_Iterator) return String is abstract; generic type T is limited new Util.Beans.Basic.Readonly_Bean with private; type T_Access is access all T'Class; function Get_Bean (Iter : in Proxy_Iterator'Class) return T_Access; -- ------------------------------ -- Iterator -- ------------------------------ -- The `Iterator_Bean` interface allows to create an iterator on the bean object -- to iterate over its internal values. The `First` and `Last` function must -- create an instance of a `Proxy_Iterator` interface which provides the -- operations to iterate. type Iterator_Bean is limited interface; type Iterator_Bean_Access is access all Iterator_Bean'Class; -- Get an iterator to iterate starting with the first element. function First (From : in Iterator_Bean) return Proxy_Iterator_Access is abstract; -- Get an iterator to iterate starting with the last element. function Last (From : in Iterator_Bean) return Proxy_Iterator_Access is abstract; private type Iterator is new Controlled with record Iter : Proxy_Iterator_Access; end record; overriding procedure Adjust (Iter : in out Iterator); overriding procedure Finalize (Iter : in out Iterator); type Proxy_Iterator is abstract new Ada.Finalization.Limited_Controlled with record Ref_Counter : Util.Concurrent.Counters.Counter; Proxy : Bean_Proxy_Access; end record; type Proxy_Map_Iterator is abstract new Proxy_Iterator with null record; package Iter is type Forward_Iterator is limited new Object_Iterator_Interfaces.Forward_Iterator with record Iter : Iterator; end record; overriding function First (Object : in Forward_Iterator) return Iterator; overriding function Next (Object : in Forward_Iterator; Pos : in Iterator) return Iterator; end Iter; end Util.Beans.Objects.Iterators;
----------------------------------------------------------------------- -- util-beans-objects-iterators -- Iterators for objects -- 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 Ada.Finalization; with Ada.Iterator_Interfaces; with Util.Beans.Basic; -- == Object iterator == -- Iterators are provided by the `Util.Beans.Objects.Iterators` package. -- The iterator instance is created by using either the `First` or `Last` -- function on the object to iterate. -- -- with Util.Beans.Objects.Iterators; -- ... -- Iter : Util.Beans.Objects.Iterators.Iterator -- := Util.Beans.Objects.Iterators.First (Object); -- -- The iterator is used in conjunction with its `Has_Element` function -- and either its `Next` or `Previous` procedure. The current element -- is obtained by using the `Element` function. When the object being -- iterated is a map, a key can be associated with the element and -- is obtained by the `Key` function. -- -- while Util.Beans.Objects.Iterators.Has_Element (Iter) loop -- declare -- Item : Object := Util.Beans.Objects.Iterators.Element (Iter); -- Key : String := Util.Beans.Objects.Iterators.Key (Iter); -- begin -- ... -- Util.Beans.Objects.Iterators.Next (Iter); -- end; -- end loop; -- package Util.Beans.Objects.Iterators is type Iterator is tagged private; -- Returns True if the iterator provides a key for each element. function Has_Key (Iter : in Iterator) return Boolean; -- Returns True if the iterator has an element. function Has_Element (Iter : in Iterator) return Boolean; -- Returns the current iterator element or Null_Object if it is empty. function Element (Iter : in Iterator) return Object; -- Returns the key associated with the current element. function Key (Iter : in Iterator) return String; -- Move the iterator to the next element. procedure Next (Iter : in out Iterator); -- Move the iterator to the previous element. procedure Previous (Iter : in out Iterator); -- Create an iterator to iterate from the first element. function First (Item : in Object) return Iterator; -- Create an iterator to iterate from the last element. function Last (Item : in Object) return Iterator; package Object_Iterator_Interfaces is new Ada.Iterator_Interfaces (Iterator, Has_Element); function Iterate (Item : in Object) return Object_Iterator_Interfaces.Forward_Iterator'Class; -- ------------------------------ -- Proxy_Iterator -- ------------------------------ -- The `Proxy_Iterator` is the base type for the implementation of an iterator. -- An instance is created by the `Iterator_Bean` interface. -- The `Porxy_Map_Iterator` extends the iterator to provide access to -- the key when the iterator gives access to the elements of a map. type Proxy_Iterator is abstract new Ada.Finalization.Limited_Controlled with private; type Proxy_Iterator_Access is access all Proxy_Iterator'Class; overriding procedure Finalize (Proxy : in out Proxy_Iterator); function Has_Element (Iter : in Proxy_Iterator) return Boolean is abstract; procedure Next (Iter : in out Proxy_Iterator) is abstract; procedure Previous (Iter : in out Proxy_Iterator) is abstract; function Element (Iter : in Proxy_Iterator) return Object is abstract; type Proxy_Map_Iterator is abstract new Proxy_Iterator with private; type Proxy_Map_Iterator_Access is access all Proxy_Map_Iterator'Class; function Key (Iter : in Proxy_Map_Iterator) return String is abstract; generic type T is limited new Util.Beans.Basic.Readonly_Bean with private; type T_Access is access all T'Class; function Get_Bean (Iter : in Proxy_Iterator'Class) return T_Access; -- ------------------------------ -- Iterator -- ------------------------------ -- The `Iterator_Bean` interface allows to create an iterator on the bean object -- to iterate over its internal values. The `First` and `Last` function must -- create an instance of a `Proxy_Iterator` interface which provides the -- operations to iterate. type Iterator_Bean is limited interface; type Iterator_Bean_Access is access all Iterator_Bean'Class; -- Get an iterator to iterate starting with the first element. function First (From : in Iterator_Bean) return Proxy_Iterator_Access is abstract; -- Get an iterator to iterate starting with the last element. function Last (From : in Iterator_Bean) return Proxy_Iterator_Access is abstract; private type Iterator is new Controlled with record Iter : Proxy_Iterator_Access; end record; overriding procedure Adjust (Iter : in out Iterator); overriding procedure Finalize (Iter : in out Iterator); type Proxy_Iterator is abstract new Ada.Finalization.Limited_Controlled with record Ref_Counter : Util.Concurrent.Counters.Counter; Proxy : Bean_Proxy_Access; end record; type Proxy_Map_Iterator is abstract new Proxy_Iterator with null record; package Iter is type Forward_Iterator is limited new Object_Iterator_Interfaces.Forward_Iterator with record Iter : Iterator; end record; overriding function First (Object : in Forward_Iterator) return Iterator; overriding function Next (Object : in Forward_Iterator; Pos : in Iterator) return Iterator; end Iter; end Util.Beans.Objects.Iterators;
Add missing with Util.Beans.Basic (problem not detected by GNAT 2021...)
Add missing with Util.Beans.Basic (problem not detected by GNAT 2021...)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a5f7c8028a36798c0b0b1107b30943281d3ce82c
awa/awaunit/awa-tests.adb
awa/awaunit/awa-tests.adb
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- 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.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with ASF.Server.Web; with ASF.Tests; -- with AWA.Applications; with AWA.Applications.Factory; with AWA.Services.Filters; with AWA.Services.Contexts; package body AWA.Tests is protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new AWA.Applications.Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; end AWA.Tests;
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- 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.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with ASF.Server.Web; with Util.Log.Loggers; with ASF.Tests; -- with AWA.Applications; with AWA.Applications.Factory; with AWA.Services.Filters; with AWA.Services.Contexts; package body AWA.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests"); protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Setup test {0}", T.Get_Name); ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new AWA.Applications.Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; end AWA.Tests;
Add a log message to help in trouble shotting unit tests
Add a log message to help in trouble shotting unit tests
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
60f5c8fd887d0ea8494adb87aedbc24326ceffba
tools/druss-commands-wifi.ads
tools/druss-commands-wifi.ads
----------------------------------------------------------------------- -- druss-commands-wifi -- Wifi related commands -- 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. ----------------------------------------------------------------------- package Druss.Commands.Wifi is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; -- Enable or disable with wifi radio. procedure Do_Enable (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type); -- Execute the wifi 'status' command to print the Wifi current status. procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type); -- Execute a command to control or get status about the Wifi. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type); end Druss.Commands.Wifi;
----------------------------------------------------------------------- -- druss-commands-wifi -- Wifi related commands -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Druss.Commands.Wifi is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; -- Enable or disable with wifi radio. procedure Do_Enable (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type); -- Execute the wifi 'status' command to print the Wifi current status. procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type); -- Execute a command to control or get status about the Wifi. overriding procedure Execute (Command : in out 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 out Command_Type; Context : in out Context_Type); end Druss.Commands.Wifi;
Change Help command to accept in out command
Change Help command to accept in out command
Ada
apache-2.0
stcarrez/bbox-ada-api
05492b098cb6b9a6a06cee25567c83105ac1a276
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Blogs.Models; with AWA.Counters.Definition; with Security.Permissions; -- == Integration == -- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application. -- It provides operations that are used by the blog beans or other services to create and update -- posts. An instance of the <tt>Blog_Module</tt> 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 -- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Blogs.Modules.NAME, -- URI => "blogs", -- Module => App.Blog_Module'Access); -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post"); -- Define the read post counter. package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count"); Not_Found : exception; type Blog_Module is new AWA.Modules.Module with private; type Blog_Module_Access is access all Blog_Module'Class; -- Initialize the blog module. overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the blog module instance associated with the current application. function Get_Blog_Module return Blog_Module_Access; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Module; Workspace_Id : in ADO.Identifier; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier); private type Blog_Module is new AWA.Modules.Module with null record; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Blogs.Models; with AWA.Counters.Definition; with Security.Permissions; -- == Integration == -- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application. -- It provides operations that are used by the blog beans or other services to create and update -- posts. An instance of the <tt>Blog_Module</tt> 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 -- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Blogs.Modules.NAME, -- URI => "blogs", -- Module => App.Blog_Module'Access); -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post"); -- Define the read post counter. package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count"); Not_Found : exception; type Blog_Module is new AWA.Modules.Module with private; type Blog_Module_Access is access all Blog_Module'Class; -- Initialize the blog module. overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the blog module instance associated with the current application. function Get_Blog_Module return Blog_Module_Access; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier); private type Blog_Module is new AWA.Modules.Module with null record; end AWA.Blogs.Modules;
Remove the Workspace_Id parameter for the Create_Blog procedure because we don't use it
Remove the Workspace_Id parameter for the Create_Blog procedure because we don't use it
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
fcbe0605e5a15a1d3b45cff697e47aeacd579824
src/wiki-attributes.ads
src/wiki-attributes.ads
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Strings; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- === Attributes === -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List</tt> -- with some operations to append or query for an attribute. package Wiki.Attributes is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List is private; -- Find the attribute with the given name. function Find (List : in Attribute_List; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Unbounded_Wide_Wide_String; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List); -- Iterate over the list attributes and call the <tt>Process</tt> procedure. procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)); private type Attribute (Name_Length, Value_Length : Natural) is limited new Util.Refs.Ref_Entity with record Name : String (1 .. Name_Length); Value : Wiki.Strings.WString (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Refs is new Util.Refs.Indefinite_References (Attribute, Attribute_Access); use Attribute_Refs; subtype Attribute_Ref is Attribute_Refs.Ref; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Ref); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List); end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- === Attributes === -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List</tt> -- with some operations to append or query for an attribute. package Wiki.Attributes is pragma Preelaborate; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Wiki.Strings.UString; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List is private; -- Find the attribute with the given name. function Find (List : in Attribute_List; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.UString; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.UString; Value : in Wiki.Strings.UString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List); -- Iterate over the list attributes and call the <tt>Process</tt> procedure. procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)); private type Attribute (Name_Length, Value_Length : Natural) is limited new Util.Refs.Ref_Entity with record Name : String (1 .. Name_Length); Value : Wiki.Strings.WString (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Refs is new Util.Refs.Indefinite_References (Attribute, Attribute_Access); use Attribute_Refs; subtype Attribute_Ref is Attribute_Refs.Ref; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Ref); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List); end Wiki.Attributes;
Use the Wiki.Strings.UString type
Use the Wiki.Strings.UString type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
37d71c71d28809f14bc1c149665455421c6d11a4
src/natools-smaz_implementations-base_64.adb
src/natools-smaz_implementations-base_64.adb
------------------------------------------------------------------------------ -- Copyright (c) 2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Implementations.Base_64 is package Tools renames Natools.Smaz_Implementations.Base_64_Tools; use type Ada.Streams.Stream_Element_Offset; use type Tools.Base_64_Digit; ---------------------- -- Public Interface -- ---------------------- procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Verbatim_Length : out Natural; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Ignored : String (1 .. 2); Offset_Backup : Ada.Streams.Stream_Element_Offset; begin Tools.Next_Digit (Input, Offset, Code); if Code <= Last_Code then Verbatim_Length := 0; elsif Variable_Length_Verbatim then Verbatim_Length := 64 - Natural (Code); Code := 0; elsif Code = 63 then Tools.Next_Digit (Input, Offset, Code); Verbatim_Length := Natural (Code) * 3 + 3; Code := 0; elsif Code = 62 then Offset_Backup := Offset; Tools.Decode_Single (Input, Offset, Ignored (1), Code); Verbatim_Length := Natural (Code) * 3 + 1; Offset := Offset_Backup; Code := 0; else Offset_Backup := Offset; Verbatim_Length := (61 - Natural (Code)) * 4; Tools.Decode_Double (Input, Offset, Ignored, Code); Verbatim_Length := (Verbatim_Length + Natural (Code)) * 3 + 2; Offset := Offset_Backup; Code := 0; end if; end Read_Code; procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String) is Ignored : Tools.Base_64_Digit; Output_Index : Natural := Output'First - 1; begin if Output'Length mod 3 = 1 then Tools.Decode_Single (Input, Offset, Output (Output_Index + 1), Ignored); Output_Index := Output_Index + 1; elsif Output'Length mod 3 = 2 then Tools.Decode_Double (Input, Offset, Output (Output_Index + 1 .. Output_Index + 2), Ignored); Output_Index := Output_Index + 2; end if; if Output_Index < Output'Last then Tools.Decode (Input, Offset, Output (Output_Index + 1 .. Output'Last)); end if; end Read_Verbatim; procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive) is Code : Tools.Base_64_Digit; begin for I in 1 .. Tools.Image_Length (Verbatim_Length) loop Tools.Next_Digit (Input, Offset, Code); end loop; end Skip_Verbatim; function Verbatim_Size (Input_Length : in Positive; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count is begin if Variable_Length_Verbatim then declare Largest_Run : constant Positive := 63 - Natural (Last_Code); Run_Count : constant Positive := (Input_Length + Largest_Run - 1) / Largest_Run; Last_Run_Size : constant Positive := Input_Length - (Run_Count - 1) * Largest_Run; begin return Ada.Streams.Stream_Element_Count (Run_Count - 1) * (Tools.Image_Length (Largest_Run) + 1) + Tools.Image_Length (Last_Run_Size) + 1; end; else declare Largest_Prefix : constant Natural := (case Input_Length mod 3 is when 1 => 15 * 3 + 1, when 2 => ((62 - Natural (Last_Code)) * 4 - 1) * 3 + 2, when others => 0); Prefix_Header_Size : constant Ada.Streams.Stream_Element_Count := (if Largest_Prefix > 0 then 1 else 0); Largest_Run : constant Positive := 64 * 3; Prefix_Size : constant Natural := Natural'Min (Largest_Prefix, Input_Length); Run_Count : constant Natural := (Input_Length - Prefix_Size + Largest_Run - 1) / Largest_Run; begin if Run_Count > 0 then return Prefix_Header_Size + Tools.Image_Length (Prefix_Size) + Ada.Streams.Stream_Element_Count (Run_Count - 1) * (Tools.Image_Length (Largest_Run) + 2) + Tools.Image_Length (Input_Length - Prefix_Size - (Run_Count - 1) * Largest_Run) + 2; else return Prefix_Header_Size + Tools.Image_Length (Prefix_Size); end if; end; end if; end Verbatim_Size; procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit) is begin Output (Offset) := Tools.Image (Code); Offset := Offset + 1; end Write_Code; procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Index : Positive := Input'First; begin if Variable_Length_Verbatim then declare Largest_Run : constant Positive := 63 - Natural (Last_Code); Length, Last : Positive; begin while Index in Input'Range loop Length := Positive'Min (Largest_Run, Input'Last + 1 - Index); Last := Index + Length - 1; Output (Offset) := Tools.Image (63 - Tools.Base_64_Digit (Length - 1)); Offset := Offset + 1; Tools.Encode (Input (Index .. Last), Output, Offset); Index := Last + 1; end loop; end; else if Input'Length mod 3 = 1 then declare Extra_Blocks : constant Natural := Natural'Min (15, Input'Length / 3); begin Output (Offset) := Tools.Image (62); Offset := Offset + 1; Tools.Encode_Single (Input (Index), Tools.Single_Byte_Padding (Extra_Blocks), Output, Offset); Index := Index + 1; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; elsif Input'Length mod 3 = 2 then declare Extra_Blocks : constant Natural := Natural'Min (Input'Length / 3, (62 - Natural (Last_Code)) * 4 - 1); begin Output (Offset) := Tools.Image (61 - Tools.Base_64_Digit (Extra_Blocks / 4)); Offset := Offset + 1; Tools.Encode_Double (Input (Index .. Index + 1), Tools.Double_Byte_Padding (Extra_Blocks mod 4), Output, Offset); Index := Index + 2; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; end if; pragma Assert ((Input'Last + 1 - Index) mod 3 = 0); while Index <= Input'Last loop declare Block_Count : constant Natural := Natural'Min (64, (Input'Last + 1 - Index) / 3); begin Output (Offset) := Tools.Image (63); Output (Offset + 1) := Tools.Image (Tools.Base_64_Digit (Block_Count - 1)); Offset := Offset + 2; Tools.Encode (Input (Index .. Index + Block_Count * 3 - 1), Output, Offset); Index := Index + Block_Count * 3; end; end loop; end if; end Write_Verbatim; end Natools.Smaz_Implementations.Base_64;
------------------------------------------------------------------------------ -- Copyright (c) 2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Implementations.Base_64 is package Tools renames Natools.Smaz_Implementations.Base_64_Tools; use type Ada.Streams.Stream_Element_Offset; use type Tools.Base_64_Digit; ---------------------- -- Public Interface -- ---------------------- procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Verbatim_Length : out Natural; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Ignored : String (1 .. 2); Offset_Backup : Ada.Streams.Stream_Element_Offset; begin Tools.Next_Digit (Input, Offset, Code); if Code <= Last_Code then Verbatim_Length := 0; elsif Variable_Length_Verbatim then if Code < 63 then Verbatim_Length := 63 - Natural (Code); else Tools.Next_Digit (Input, Offset, Code); Verbatim_Length := Natural (Code) + 63 - Natural (Last_Code); end if; Code := 0; elsif Code = 63 then Tools.Next_Digit (Input, Offset, Code); Verbatim_Length := Natural (Code) * 3 + 3; Code := 0; elsif Code = 62 then Offset_Backup := Offset; Tools.Decode_Single (Input, Offset, Ignored (1), Code); Verbatim_Length := Natural (Code) * 3 + 1; Offset := Offset_Backup; Code := 0; else Offset_Backup := Offset; Verbatim_Length := (61 - Natural (Code)) * 4; Tools.Decode_Double (Input, Offset, Ignored, Code); Verbatim_Length := (Verbatim_Length + Natural (Code)) * 3 + 2; Offset := Offset_Backup; Code := 0; end if; end Read_Code; procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String) is Ignored : Tools.Base_64_Digit; Output_Index : Natural := Output'First - 1; begin if Output'Length mod 3 = 1 then Tools.Decode_Single (Input, Offset, Output (Output_Index + 1), Ignored); Output_Index := Output_Index + 1; elsif Output'Length mod 3 = 2 then Tools.Decode_Double (Input, Offset, Output (Output_Index + 1 .. Output_Index + 2), Ignored); Output_Index := Output_Index + 2; end if; if Output_Index < Output'Last then Tools.Decode (Input, Offset, Output (Output_Index + 1 .. Output'Last)); end if; end Read_Verbatim; procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive) is Code : Tools.Base_64_Digit; begin for I in 1 .. Tools.Image_Length (Verbatim_Length) loop Tools.Next_Digit (Input, Offset, Code); end loop; end Skip_Verbatim; function Verbatim_Size (Input_Length : in Positive; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count is begin if Variable_Length_Verbatim then declare Largest_Single : constant Positive := 62 - Natural (Last_Code); Largest_Run : constant Positive := 64 + Largest_Single; Run_Count : constant Natural := (Input_Length + Largest_Run - 1) / Largest_Run; Last_Run_Size : constant Positive := Input_Length - (Run_Count - 1) * Largest_Run; Last_Run_Header_Size : constant Ada.Streams.Stream_Element_Count := (if Last_Run_Size > Largest_Single then 2 else 1); begin return Ada.Streams.Stream_Element_Count (Run_Count) * (Tools.Image_Length (Largest_Run) + 2) + Tools.Image_Length (Last_Run_Size) + Last_Run_Header_Size; end; else declare Largest_Prefix : constant Natural := (case Input_Length mod 3 is when 1 => 15 * 3 + 1, when 2 => ((62 - Natural (Last_Code)) * 4 - 1) * 3 + 2, when others => 0); Prefix_Header_Size : constant Ada.Streams.Stream_Element_Count := (if Largest_Prefix > 0 then 1 else 0); Largest_Run : constant Positive := 64 * 3; Prefix_Size : constant Natural := Natural'Min (Largest_Prefix, Input_Length); Run_Count : constant Natural := (Input_Length - Prefix_Size + Largest_Run - 1) / Largest_Run; begin if Run_Count > 0 then return Prefix_Header_Size + Tools.Image_Length (Prefix_Size) + Ada.Streams.Stream_Element_Count (Run_Count - 1) * (Tools.Image_Length (Largest_Run) + 2) + Tools.Image_Length (Input_Length - Prefix_Size - (Run_Count - 1) * Largest_Run) + 2; else return Prefix_Header_Size + Tools.Image_Length (Prefix_Size); end if; end; end if; end Verbatim_Size; procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit) is begin Output (Offset) := Tools.Image (Code); Offset := Offset + 1; end Write_Code; procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Index : Positive := Input'First; begin if Variable_Length_Verbatim then declare Largest_Single : constant Positive := 62 - Natural (Last_Code); Largest_Run : constant Positive := 64 + Largest_Single; Length, Last : Natural; begin while Index in Input'Range loop Length := Positive'Min (Largest_Run, Input'Last + 1 - Index); if Length > Largest_Single then Write_Code (Output, Offset, 63); Write_Code (Output, Offset, Tools.Base_64_Digit (Length - Largest_Single - 1)); else Write_Code (Output, Offset, Tools.Base_64_Digit (63 - Length)); end if; if Length mod 3 = 1 then Tools.Encode_Single (Input (Index), 0, Output, Offset); Index := Index + 1; Length := Length - 1; elsif Length mod 3 = 2 then Tools.Encode_Double (Input (Index .. Index + 1), 0, Output, Offset); Index := Index + 2; Length := Length - 2; end if; if Length > 0 then Last := Index + Length - 1; Tools.Encode (Input (Index .. Last), Output, Offset); Index := Last + 1; end if; end loop; end; else if Input'Length mod 3 = 1 then declare Extra_Blocks : constant Natural := Natural'Min (15, Input'Length / 3); begin Output (Offset) := Tools.Image (62); Offset := Offset + 1; Tools.Encode_Single (Input (Index), Tools.Single_Byte_Padding (Extra_Blocks), Output, Offset); Index := Index + 1; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; elsif Input'Length mod 3 = 2 then declare Extra_Blocks : constant Natural := Natural'Min (Input'Length / 3, (62 - Natural (Last_Code)) * 4 - 1); begin Output (Offset) := Tools.Image (61 - Tools.Base_64_Digit (Extra_Blocks / 4)); Offset := Offset + 1; Tools.Encode_Double (Input (Index .. Index + 1), Tools.Double_Byte_Padding (Extra_Blocks mod 4), Output, Offset); Index := Index + 2; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; end if; pragma Assert ((Input'Last + 1 - Index) mod 3 = 0); while Index <= Input'Last loop declare Block_Count : constant Natural := Natural'Min (64, (Input'Last + 1 - Index) / 3); begin Output (Offset) := Tools.Image (63); Output (Offset + 1) := Tools.Image (Tools.Base_64_Digit (Block_Count - 1)); Offset := Offset + 2; Tools.Encode (Input (Index .. Index + Block_Count * 3 - 1), Output, Offset); Index := Index + Block_Count * 3; end; end loop; end if; end Write_Verbatim; end Natools.Smaz_Implementations.Base_64;
rewrite variable-length verbatim code
smaz_implementations-base_64: rewrite variable-length verbatim code At some point in the development I changed the base-64 scheme, but failed to propagate it everywhere. Mostly I intend to use only one mode in base-64, and the other one is merely a place-holder, which explains how it got neglected. Now at least it works, even if it's useless.
Ada
isc
faelys/natools
0d4e984029346d2e919133b1e4b8128713f01238
src/drivers/adabase-driver-base-postgresql.adb
src/drivers/adabase-driver-base-postgresql.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt package body AdaBase.Driver.Base.PostgreSQL is ------------------------ -- last_driver_code -- ------------------------ overriding function last_sql_state (driver : PostgreSQL_Driver) return TSqlState is -- Polled by driver.execute before result is cleared begin return driver.connection.SqlState; end last_sql_state; ------------------------ -- last_driver_code -- ------------------------ overriding function last_driver_code (driver : PostgreSQL_Driver) return DriverCodes is begin return driver.connection.driverCode; end last_driver_code; --------------------------- -- last_driver_message -- --------------------------- overriding function last_driver_message (driver : PostgreSQL_Driver) return String is begin return driver.connection.driverMessage; end last_driver_message; ---------------------- -- last_insert_id -- ---------------------- overriding function last_insert_id (driver : PostgreSQL_Driver) return TraxID is begin return driver.connection.lastInsertID; end last_insert_id; ------------------ -- disconnect -- ------------------ overriding procedure disconnect (driver : out PostgreSQL_Driver) is begin -- TO BE IMPLEMENTED null; end disconnect; -------------- -- commit -- -------------- overriding procedure commit (driver : PostgreSQL_Driver) is begin -- TO BE IMPLEMENTED null; end commit; ---------------- -- rollback -- ---------------- overriding procedure rollback (driver : PostgreSQL_Driver) is begin -- TO BE IMPLEMENTED null; end rollback; -- ------------- -- -- query -- -- ------------- -- function query (driver : PostgreSQL_Driver; sql : String) -- return SMT.PostgreSQL_statement is -- begin -- -- TO BE IMPLEMENTED -- raise CON.UNSUPPORTED_BY_PGSQL; -- end query; -- -- function prepare (driver : PostgreSQL_Driver; sql : String) -- return SMT.PostgreSQL_statement is -- begin -- -- TO BE IMPLEMENTED -- raise CON.UNSUPPORTED_BY_PGSQL; -- end prepare; -- -- -- -------------------- -- -- query_select -- -- -------------------- -- function query_select (driver : PostgreSQL_Driver; -- distinct : Boolean := False; -- tables : String; -- columns : String; -- conditions : String := blankstring; -- groupby : String := blankstring; -- having : String := blankstring; -- order : String := blankstring; -- null_sort : NullPriority := native; -- limit : TraxID := 0; -- offset : TraxID := 0) -- return SMT.PostgreSQL_statement is -- begin -- -- TO BE IMPLEMENTED -- raise CON.UNSUPPORTED_BY_PGSQL; -- end query_select; -- -- -- ---------------------- -- -- prepare_select -- -- ---------------------- -- function prepare_select (driver : PostgreSQL_Driver; -- distinct : Boolean := False; -- tables : String; -- columns : String; -- conditions : String := blankstring; -- groupby : String := blankstring; -- having : String := blankstring; -- order : String := blankstring; -- null_sort : NullPriority := native; -- limit : TraxID := 0; -- offset : TraxID := 0) -- return SMT.PostgreSQL_statement is -- begin -- -- TO BE IMPLEMENTED -- raise CON.UNSUPPORTED_BY_PGSQL; -- end prepare_select; ------------------ -- initialize -- ------------------ overriding procedure initialize (Object : in out PostgreSQL_Driver) is begin Object.connection := Object.local_connection'Unchecked_Access; Object.dialect := driver_postgresql; end initialize; ------------------------ -- basic_connect #1 -- ------------------------ overriding procedure basic_connect (driver : out PostgreSQL_Driver; database : String; username : String := blankstring; password : String := blankstring; socket : String := blankstring) is begin driver.private_connect (database => database, username => username, password => password, socket => socket); end basic_connect; ------------------------ -- basic_connect #2 -- ------------------------ overriding procedure basic_connect (driver : out PostgreSQL_Driver; database : String; username : String := blankstring; password : String := blankstring; hostname : String := blankstring; port : PosixPort) is begin driver.private_connect (database => database, username => username, password => password, hostname => hostname, port => port); end basic_connect; ----------------------- -- private_connect -- ----------------------- procedure private_connect (driver : out PostgreSQL_Driver; database : String; username : String; password : String; hostname : String := blankstring; socket : String := blankstring; port : PosixPort := portless) is err1 : constant CT.Text := CT.SUS ("ACK! Reconnection attempted on active connection"); nom : constant CT.Text := CT.SUS ("Connection to " & database & " database succeeded."); begin if driver.connection_active then driver.log_problem (category => execution, message => err1); return; end if; driver.connection.connect (database => database, username => username, password => password, socket => socket, hostname => hostname, port => port); driver.connection_active := driver.connection.connected; driver.log_nominal (category => connecting, message => nom); exception when Error : others => driver.log_problem (category => connecting, break => True, message => CT.SUS (CON.EX.Exception_Message (X => Error))); end private_connect; --------------- -- execute -- --------------- overriding function execute (driver : PostgreSQL_Driver; sql : String) return AffectedRows is trsql : String := CT.trim_sql (sql); nquery : Natural := CT.count_queries (trsql); aborted : constant AffectedRows := 0; err1 : constant CT.Text := CT.SUS ("ACK! Execution attempted on inactive connection"); err2 : constant String := "Driver is configured to allow only one query at " & "time, but this SQL contains multiple queries: "; begin if not driver.connection_active then -- Fatal attempt to query an unccnnected database driver.log_problem (category => execution, message => err1, break => True); return aborted; end if; if nquery > 1 and then not driver.trait_multiquery_enabled then -- Fatal attempt to execute multiple queries when it's not permitted driver.log_problem (category => execution, message => CT.SUS (err2 & trsql), break => True); return aborted; end if; declare result : AffectedRows; begin for query_index in Positive range 1 .. nquery loop result := 0; if nquery = 1 then driver.connection.execute (trsql); driver.log_nominal (execution, CT.SUS (trsql)); else declare SQ : constant String := CT.subquery (trsql, query_index); begin driver.connection.execute (SQ); driver.log_nominal (execution, CT.SUS (SQ)); end; end if; end loop; result := driver.connection.rows_affected_by_execution; return result; exception when CON.QUERY_FAIL => driver.log_problem (category => execution, message => CT.SUS (sql), pull_codes => True); return aborted; end; end execute; end AdaBase.Driver.Base.PostgreSQL;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt package body AdaBase.Driver.Base.PostgreSQL is ------------------------ -- last_driver_code -- ------------------------ overriding function last_sql_state (driver : PostgreSQL_Driver) return TSqlState is -- Polled by driver.execute before result is cleared begin return driver.connection.SqlState; end last_sql_state; ------------------------ -- last_driver_code -- ------------------------ overriding function last_driver_code (driver : PostgreSQL_Driver) return DriverCodes is begin return driver.connection.driverCode; end last_driver_code; --------------------------- -- last_driver_message -- --------------------------- overriding function last_driver_message (driver : PostgreSQL_Driver) return String is begin return driver.connection.driverMessage; end last_driver_message; ---------------------- -- last_insert_id -- ---------------------- overriding function last_insert_id (driver : PostgreSQL_Driver) return TraxID is begin return driver.connection.lastInsertID; end last_insert_id; ------------------ -- disconnect -- ------------------ overriding procedure disconnect (driver : out PostgreSQL_Driver) is begin -- TO BE IMPLEMENTED null; end disconnect; -------------- -- commit -- -------------- overriding procedure commit (driver : PostgreSQL_Driver) is use type TransIsolation; err1 : constant CT.Text := CT.SUS ("ACK! Commit attempted on inactive connection"); err2 : constant CT.Text := CT.SUS ("ACK! Commit attempted when autocommit mode set on"); err3 : constant CT.Text := CT.SUS ("Commit attempt failed"); msg1 : constant CT.Text := CT.SUS ("END TRANSACTION (COMMIT)"); begin if not driver.connection_active then -- Non-fatal attempt to commit when no database is connected driver.log_problem (category => transaction, message => err1); return; end if; if driver.connection.autoCommit then -- Non-fatal attempt to commit when autocommit is on driver.log_problem (category => transaction, message => err2); return; end if; driver.connection.commit; driver.log_nominal (category => transaction, message => msg1); exception when CON.COMMIT_FAIL => driver.log_problem (category => transaction, message => err3, pull_codes => True); end commit; ---------------- -- rollback -- ---------------- overriding procedure rollback (driver : PostgreSQL_Driver) is use type TransIsolation; err1 : constant CT.Text := CT.SUS ("ACK! Rollback attempted on inactive connection"); err2 : constant CT.Text := CT.SUS ("ACK! Rollback attempted when autocommit mode set on"); err3 : constant CT.Text := CT.SUS ("Rollback attempt failed"); begin if not driver.connection_active then -- Non-fatal attempt to roll back when no database is connected driver.log_problem (category => miscellaneous, message => err1); return; end if; if driver.connection.autoCommit then -- Non-fatal attempt to roll back when autocommit is on driver.log_problem (category => miscellaneous, message => err2); return; end if; driver.connection.rollback; exception when CON.ROLLBACK_FAIL => driver.log_problem (category => miscellaneous, message => err3, pull_codes => True); end rollback; -- ------------- -- -- query -- -- ------------- -- function query (driver : PostgreSQL_Driver; sql : String) -- return SMT.PostgreSQL_statement is -- begin -- -- TO BE IMPLEMENTED -- raise CON.UNSUPPORTED_BY_PGSQL; -- end query; -- -- function prepare (driver : PostgreSQL_Driver; sql : String) -- return SMT.PostgreSQL_statement is -- begin -- -- TO BE IMPLEMENTED -- raise CON.UNSUPPORTED_BY_PGSQL; -- end prepare; -- -- -- -------------------- -- -- query_select -- -- -------------------- -- function query_select (driver : PostgreSQL_Driver; -- distinct : Boolean := False; -- tables : String; -- columns : String; -- conditions : String := blankstring; -- groupby : String := blankstring; -- having : String := blankstring; -- order : String := blankstring; -- null_sort : NullPriority := native; -- limit : TraxID := 0; -- offset : TraxID := 0) -- return SMT.PostgreSQL_statement is -- begin -- -- TO BE IMPLEMENTED -- raise CON.UNSUPPORTED_BY_PGSQL; -- end query_select; -- -- -- ---------------------- -- -- prepare_select -- -- ---------------------- -- function prepare_select (driver : PostgreSQL_Driver; -- distinct : Boolean := False; -- tables : String; -- columns : String; -- conditions : String := blankstring; -- groupby : String := blankstring; -- having : String := blankstring; -- order : String := blankstring; -- null_sort : NullPriority := native; -- limit : TraxID := 0; -- offset : TraxID := 0) -- return SMT.PostgreSQL_statement is -- begin -- -- TO BE IMPLEMENTED -- raise CON.UNSUPPORTED_BY_PGSQL; -- end prepare_select; ------------------ -- initialize -- ------------------ overriding procedure initialize (Object : in out PostgreSQL_Driver) is begin Object.connection := Object.local_connection'Unchecked_Access; Object.dialect := driver_postgresql; end initialize; ------------------------ -- basic_connect #1 -- ------------------------ overriding procedure basic_connect (driver : out PostgreSQL_Driver; database : String; username : String := blankstring; password : String := blankstring; socket : String := blankstring) is begin driver.private_connect (database => database, username => username, password => password, socket => socket); end basic_connect; ------------------------ -- basic_connect #2 -- ------------------------ overriding procedure basic_connect (driver : out PostgreSQL_Driver; database : String; username : String := blankstring; password : String := blankstring; hostname : String := blankstring; port : PosixPort) is begin driver.private_connect (database => database, username => username, password => password, hostname => hostname, port => port); end basic_connect; ----------------------- -- private_connect -- ----------------------- procedure private_connect (driver : out PostgreSQL_Driver; database : String; username : String; password : String; hostname : String := blankstring; socket : String := blankstring; port : PosixPort := portless) is err1 : constant CT.Text := CT.SUS ("ACK! Reconnection attempted on active connection"); nom : constant CT.Text := CT.SUS ("Connection to " & database & " database succeeded."); begin if driver.connection_active then driver.log_problem (category => execution, message => err1); return; end if; driver.connection.connect (database => database, username => username, password => password, socket => socket, hostname => hostname, port => port); driver.connection_active := driver.connection.connected; driver.log_nominal (category => connecting, message => nom); exception when Error : others => driver.log_problem (category => connecting, break => True, message => CT.SUS (CON.EX.Exception_Message (X => Error))); end private_connect; --------------- -- execute -- --------------- overriding function execute (driver : PostgreSQL_Driver; sql : String) return AffectedRows is trsql : String := CT.trim_sql (sql); nquery : Natural := CT.count_queries (trsql); aborted : constant AffectedRows := 0; err1 : constant CT.Text := CT.SUS ("ACK! Execution attempted on inactive connection"); err2 : constant String := "Driver is configured to allow only one query at " & "time, but this SQL contains multiple queries: "; begin if not driver.connection_active then -- Fatal attempt to query an unccnnected database driver.log_problem (category => execution, message => err1, break => True); return aborted; end if; if nquery > 1 and then not driver.trait_multiquery_enabled then -- Fatal attempt to execute multiple queries when it's not permitted driver.log_problem (category => execution, message => CT.SUS (err2 & trsql), break => True); return aborted; end if; declare result : AffectedRows; begin for query_index in Positive range 1 .. nquery loop result := 0; if nquery = 1 then driver.connection.execute (trsql); driver.log_nominal (execution, CT.SUS (trsql)); else declare SQ : constant String := CT.subquery (trsql, query_index); begin driver.connection.execute (SQ); driver.log_nominal (execution, CT.SUS (SQ)); end; end if; end loop; result := driver.connection.rows_affected_by_execution; return result; exception when CON.QUERY_FAIL => driver.log_problem (category => execution, message => CT.SUS (sql), pull_codes => True); return aborted; end; end execute; end AdaBase.Driver.Base.PostgreSQL;
Implement PGSQL commit and rollback
Implement PGSQL commit and rollback These are virtually identical to other drivers, they are candidates to move to base driver.
Ada
isc
jrmarino/AdaBase
d6980c835547893005ed57db9d4295e940721553
src/sys/processes/util-processes.adb
src/sys/processes/util-processes.adb
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- Copyright (C) 2011, 2016, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Util.Strings; with Util.Processes.Os; package body Util.Processes is use Util.Log; use Ada.Strings.Unbounded; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Processes"); procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Processes.System_Process'Class, Name => Util.Processes.System_Process_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => File_Type_Array, Name => File_Type_Array_Access); -- ------------------------------ -- Before launching the process, redirect the input stream of the process -- to the specified file. -- ------------------------------ procedure Set_Input_Stream (Proc : in out Process; File : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set input stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.In_File := To_Unbounded_String (File); end Set_Input_Stream; -- ------------------------------ -- Set the output stream of the process. -- ------------------------------ procedure Set_Output_Stream (Proc : in out Process; File : in String; Append : in Boolean := False) is begin if Proc.Is_Running then Log.Error ("Cannot set output stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.Out_File := To_Unbounded_String (File); Proc.Out_Append := Append; end Set_Output_Stream; -- ------------------------------ -- Set the error stream of the process. -- ------------------------------ procedure Set_Error_Stream (Proc : in out Process; File : in String; Append : in Boolean := False) is begin if Proc.Is_Running then Log.Error ("Cannot set error stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.Err_File := To_Unbounded_String (File); Proc.Err_Append := Append; end Set_Error_Stream; -- ------------------------------ -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. -- ------------------------------ procedure Set_Working_Directory (Proc : in out Process; Path : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set working directory to {0} while process is running", Path); raise Invalid_State with "Process is running"; end if; Proc.Dir := To_Unbounded_String (Path); end Set_Working_Directory; -- ------------------------------ -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. -- ------------------------------ procedure Set_Shell (Proc : in out Process; Shell : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set shell to {0} while process is running", Shell); raise Invalid_State with "Process is running"; end if; Proc.Shell := To_Unbounded_String (Shell); end Set_Shell; -- ------------------------------ -- Closes the given file descriptor in the child process before executing the command. -- ------------------------------ procedure Add_Close (Proc : in out Process; Fd : in File_Type) is List : File_Type_Array_Access; begin if Proc.To_Close /= null then List := new File_Type_Array (1 .. Proc.To_Close'Last + 1); List (1 .. Proc.To_Close'Last) := Proc.To_Close.all; List (List'Last) := Fd; Free (Proc.To_Close); else List := new File_Type_Array (1 .. 1); List (1) := Fd; end if; Proc.To_Close := List; end Add_Close; -- ------------------------------ -- Append the argument to the current process argument list. -- Raises <b>Invalid_State</b> if the process is running. -- ------------------------------ procedure Append_Argument (Proc : in out Process; Arg : in String) is begin if Proc.Is_Running then Log.Error ("Cannot add argument '{0}' while process is running", Arg); raise Invalid_State with "Process is running"; end if; Proc.Sys.Append_Argument (Arg); end Append_Argument; -- ------------------------------ -- Set the environment variable to be used by the process before its creation. -- ------------------------------ procedure Set_Environment (Proc : in out Process; Name : in String; Value : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set environment '{0}' while process is running", Name); raise Invalid_State with "Process is running"; end if; Proc.Sys.Set_Environment (Name, Value); end Set_Environment; procedure Set_Environment (Proc : in out Process; Iterate : not null access procedure (Process : not null access procedure (Name : in String; Value : in String))) is procedure Process (Name, Value : in String); procedure Process (Name, Value : in String) is begin Proc.Sys.Set_Environment (Name, Value); end Process; begin if Proc.Is_Running then Log.Error ("Cannot set environment while process is running"); raise Invalid_State with "Process is running"; end if; Iterate (Process'Access); end Set_Environment; -- ------------------------------ -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. -- ------------------------------ procedure Spawn (Proc : in out Process; Command : in String; Arguments : in Argument_List; Mode : in Pipe_Mode := NONE) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); Proc.Sys.Clear_Arguments; -- Build the argc/argv table, terminated by NULL Proc.Sys.Append_Argument (Command); for I in Arguments'Range loop Proc.Sys.Append_Argument (Arguments (I).all); end loop; Spawn (Proc, Mode); end Spawn; -- ------------------------------ -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. -- ------------------------------ procedure Spawn (Proc : in out Process; Command : in String; Mode : in Pipe_Mode := NONE) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); Proc.Sys.Clear_Arguments; if Length (Proc.Shell) > 0 then Proc.Sys.Append_Argument (To_String (Proc.Shell)); Proc.Sys.Append_Argument ("-c"); Proc.Sys.Append_Argument (Command); else declare Pos : Natural := Command'First; N : Natural; begin -- Build the argc/argv table while Pos <= Command'Last loop N := Util.Strings.Index (Command, ' ', Pos); if N = 0 then N := Command'Last + 1; end if; Proc.Sys.Append_Argument (Command (Pos .. N - 1)); Pos := N + 1; end loop; end; end if; Spawn (Proc, Mode); end Spawn; -- ------------------------------ -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. -- ------------------------------ procedure Spawn (Proc : in out Process; Mode : in Pipe_Mode := NONE) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; -- Prepare to redirect the input/output/error streams. -- The pipe mode takes precedence and will override these redirections. Proc.Sys.Set_Streams (Input => To_String (Proc.In_File), Output => To_String (Proc.Out_File), Error => To_String (Proc.Err_File), Append_Output => Proc.Out_Append, Append_Error => Proc.Err_Append, To_Close => Proc.To_Close); -- System specific spawn Proc.Exit_Value := -1; Proc.Sys.Spawn (Proc, Mode); end Spawn; -- ------------------------------ -- Wait for the process to terminate. -- ------------------------------ procedure Wait (Proc : in out Process) is begin if not Is_Running (Proc) then return; end if; Log.Info ("Waiting for process {0}", Process_Identifier'Image (Proc.Pid)); Proc.Sys.Wait (Proc, -1.0); end Wait; -- ------------------------------ -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. -- ------------------------------ procedure Stop (Proc : in out Process; Signal : in Positive := 15) is begin if Is_Running (Proc) then Proc.Sys.Stop (Proc, Signal); end if; end Stop; -- ------------------------------ -- Get the process exit status. -- ------------------------------ function Get_Exit_Status (Proc : in Process) return Integer is begin return Proc.Exit_Value; end Get_Exit_Status; -- ------------------------------ -- Get the process identifier. -- ------------------------------ function Get_Pid (Proc : in Process) return Process_Identifier is begin return Proc.Pid; end Get_Pid; -- ------------------------------ -- Returns True if the process is running. -- ------------------------------ function Is_Running (Proc : in Process) return Boolean is begin return Proc.Pid > 0 and Proc.Exit_Value < 0; end Is_Running; -- ------------------------------ -- Get the process input stream allowing to write on the process standard input. -- ------------------------------ function Get_Input_Stream (Proc : in Process) return Util.Streams.Output_Stream_Access is begin return Proc.Input; end Get_Input_Stream; -- ------------------------------ -- Get the process output stream allowing to read the process standard output. -- ------------------------------ function Get_Output_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access is begin return Proc.Output; end Get_Output_Stream; -- ------------------------------ -- Get the process error stream allowing to read the process standard output. -- ------------------------------ function Get_Error_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access is begin return Proc.Error; end Get_Error_Stream; -- ------------------------------ -- Initialize the process instance. -- ------------------------------ overriding procedure Initialize (Proc : in out Process) is begin Proc.Sys := new Util.Processes.Os.System_Process; Proc.Shell := To_Unbounded_String (Util.Processes.Os.SHELL); end Initialize; -- ------------------------------ -- Deletes the process instance. -- ------------------------------ overriding procedure Finalize (Proc : in out Process) is procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Streams.Input_Stream'Class, Name => Util.Streams.Input_Stream_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Streams.Output_Stream'Class, Name => Util.Streams.Output_Stream_Access); begin if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Free (Proc.Input); Free (Proc.Output); Free (Proc.Error); Free (Proc.To_Close); end Finalize; end Util.Processes;
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- Copyright (C) 2011, 2016, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Util.Strings; with Util.Processes.Os; package body Util.Processes is use Util.Log; use Ada.Strings.Unbounded; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Processes"); procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Processes.System_Process'Class, Name => Util.Processes.System_Process_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => File_Type_Array, Name => File_Type_Array_Access); -- ------------------------------ -- Before launching the process, redirect the input stream of the process -- to the specified file. -- ------------------------------ procedure Set_Input_Stream (Proc : in out Process; File : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set input stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.In_File := To_Unbounded_String (File); end Set_Input_Stream; -- ------------------------------ -- Set the output stream of the process. -- ------------------------------ procedure Set_Output_Stream (Proc : in out Process; File : in String; Append : in Boolean := False) is begin if Proc.Is_Running then Log.Error ("Cannot set output stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.Out_File := To_Unbounded_String (File); Proc.Out_Append := Append; end Set_Output_Stream; -- ------------------------------ -- Set the error stream of the process. -- ------------------------------ procedure Set_Error_Stream (Proc : in out Process; File : in String; Append : in Boolean := False) is begin if Proc.Is_Running then Log.Error ("Cannot set error stream to {0} while process is running", File); raise Invalid_State with "Process is running"; end if; Proc.Err_File := To_Unbounded_String (File); Proc.Err_Append := Append; end Set_Error_Stream; -- ------------------------------ -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. -- ------------------------------ procedure Set_Working_Directory (Proc : in out Process; Path : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set working directory to {0} while process is running", Path); raise Invalid_State with "Process is running"; end if; Proc.Dir := To_Unbounded_String (Path); end Set_Working_Directory; -- ------------------------------ -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. -- ------------------------------ procedure Set_Shell (Proc : in out Process; Shell : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set shell to {0} while process is running", Shell); raise Invalid_State with "Process is running"; end if; Proc.Shell := To_Unbounded_String (Shell); end Set_Shell; -- ------------------------------ -- Closes the given file descriptor in the child process before executing the command. -- ------------------------------ procedure Add_Close (Proc : in out Process; Fd : in File_Type) is List : File_Type_Array_Access; begin if Proc.To_Close /= null then List := new File_Type_Array (1 .. Proc.To_Close'Last + 1); List (1 .. Proc.To_Close'Last) := Proc.To_Close.all; List (List'Last) := Fd; Free (Proc.To_Close); else List := new File_Type_Array (1 .. 1); List (1) := Fd; end if; Proc.To_Close := List; end Add_Close; -- ------------------------------ -- Append the argument to the current process argument list. -- Raises <b>Invalid_State</b> if the process is running. -- ------------------------------ procedure Append_Argument (Proc : in out Process; Arg : in String) is begin if Proc.Is_Running then Log.Error ("Cannot add argument '{0}' while process is running", Arg); raise Invalid_State with "Process is running"; end if; Proc.Sys.Append_Argument (Arg); end Append_Argument; -- ------------------------------ -- Set the environment variable to be used by the process before its creation. -- ------------------------------ procedure Set_Environment (Proc : in out Process; Name : in String; Value : in String) is begin if Proc.Is_Running then Log.Error ("Cannot set environment '{0}' while process is running", Name); raise Invalid_State with "Process is running"; end if; Proc.Sys.Set_Environment (Name, Value); end Set_Environment; procedure Set_Environment (Proc : in out Process; Iterate : not null access procedure (Process : not null access procedure (Name : in String; Value : in String))) is procedure Process (Name, Value : in String); procedure Process (Name, Value : in String) is begin Proc.Sys.Set_Environment (Name, Value); end Process; begin if Proc.Is_Running then Log.Error ("Cannot set environment while process is running"); raise Invalid_State with "Process is running"; end if; Iterate (Process'Access); end Set_Environment; -- ------------------------------ -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. -- ------------------------------ procedure Spawn (Proc : in out Process; Command : in String; Arguments : in Argument_List; Mode : in Pipe_Mode := NONE) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); Proc.Sys.Clear_Arguments; -- Build the argc/argv table, terminated by NULL Proc.Sys.Append_Argument (Command); for I in Arguments'Range loop Proc.Sys.Append_Argument (Arguments (I).all); end loop; Spawn (Proc, Mode); end Spawn; procedure Spawn (Proc : in out Process; Arguments : in Util.Strings.Vectors.Vector; Mode : in Pipe_Mode := NONE) is Command : constant String := Arguments.First_Element; begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); Proc.Sys.Clear_Arguments; -- Build the argc/argv table, terminated by NULL for Argument of Arguments loop Proc.Sys.Append_Argument (Argument); end loop; Spawn (Proc, Mode); end Spawn; -- ------------------------------ -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. -- ------------------------------ procedure Spawn (Proc : in out Process; Command : in String; Mode : in Pipe_Mode := NONE) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); Proc.Sys.Clear_Arguments; if Length (Proc.Shell) > 0 then Proc.Sys.Append_Argument (To_String (Proc.Shell)); Proc.Sys.Append_Argument ("-c"); Proc.Sys.Append_Argument (Command); else declare Pos : Natural := Command'First; N : Natural; begin -- Build the argc/argv table while Pos <= Command'Last loop N := Util.Strings.Index (Command, ' ', Pos); if N = 0 then N := Command'Last + 1; end if; Proc.Sys.Append_Argument (Command (Pos .. N - 1)); Pos := N + 1; end loop; end; end if; Spawn (Proc, Mode); end Spawn; -- ------------------------------ -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. -- ------------------------------ procedure Spawn (Proc : in out Process; Mode : in Pipe_Mode := NONE) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; -- Prepare to redirect the input/output/error streams. -- The pipe mode takes precedence and will override these redirections. Proc.Sys.Set_Streams (Input => To_String (Proc.In_File), Output => To_String (Proc.Out_File), Error => To_String (Proc.Err_File), Append_Output => Proc.Out_Append, Append_Error => Proc.Err_Append, To_Close => Proc.To_Close); -- System specific spawn Proc.Exit_Value := -1; Proc.Sys.Spawn (Proc, Mode); end Spawn; -- ------------------------------ -- Wait for the process to terminate. -- ------------------------------ procedure Wait (Proc : in out Process) is begin if not Is_Running (Proc) then return; end if; Log.Info ("Waiting for process {0}", Process_Identifier'Image (Proc.Pid)); Proc.Sys.Wait (Proc, -1.0); end Wait; -- ------------------------------ -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. -- ------------------------------ procedure Stop (Proc : in out Process; Signal : in Positive := 15) is begin if Is_Running (Proc) then Proc.Sys.Stop (Proc, Signal); end if; end Stop; -- ------------------------------ -- Get the process exit status. -- ------------------------------ function Get_Exit_Status (Proc : in Process) return Integer is begin return Proc.Exit_Value; end Get_Exit_Status; -- ------------------------------ -- Get the process identifier. -- ------------------------------ function Get_Pid (Proc : in Process) return Process_Identifier is begin return Proc.Pid; end Get_Pid; -- ------------------------------ -- Returns True if the process is running. -- ------------------------------ function Is_Running (Proc : in Process) return Boolean is begin return Proc.Pid > 0 and Proc.Exit_Value < 0; end Is_Running; -- ------------------------------ -- Get the process input stream allowing to write on the process standard input. -- ------------------------------ function Get_Input_Stream (Proc : in Process) return Util.Streams.Output_Stream_Access is begin return Proc.Input; end Get_Input_Stream; -- ------------------------------ -- Get the process output stream allowing to read the process standard output. -- ------------------------------ function Get_Output_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access is begin return Proc.Output; end Get_Output_Stream; -- ------------------------------ -- Get the process error stream allowing to read the process standard output. -- ------------------------------ function Get_Error_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access is begin return Proc.Error; end Get_Error_Stream; -- ------------------------------ -- Initialize the process instance. -- ------------------------------ overriding procedure Initialize (Proc : in out Process) is begin Proc.Sys := new Util.Processes.Os.System_Process; Proc.Shell := To_Unbounded_String (Util.Processes.Os.SHELL); end Initialize; -- ------------------------------ -- Deletes the process instance. -- ------------------------------ overriding procedure Finalize (Proc : in out Process) is procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Streams.Input_Stream'Class, Name => Util.Streams.Input_Stream_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Streams.Output_Stream'Class, Name => Util.Streams.Output_Stream_Access); begin if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Free (Proc.Input); Free (Proc.Output); Free (Proc.Error); Free (Proc.To_Close); end Finalize; end Util.Processes;
Add new Spawn procedure with a String vector for the arguments
Add new Spawn procedure with a String vector for the arguments
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d514c219fdebaf5873c75464c6b19a44b2d7b111
src/ado-queries.ads
src/ado-queries.ads
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; with Interfaces; with Ada.Strings.Unbounded; -- == Introduction == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application. -- The benefit of the framework are the following: -- -- * The SQL query result are directly mapped in Ada records, -- * It is easy to change or tune an SQL query without re-building the application, -- * The SQL query can be easily tuned for a given database -- -- The database query framework uses an XML query file: -- -- * The XML query file defines a mapping that represents the result of SQL queries, -- * The XML mapping is used by [http://code.google.com/p/ada-gen Dynamo] to generate an Ada record, -- * The XML query file also defines a set of SQL queries, each query being identified by a unique name, -- * The XML query file is read by the application to obtain the SQL query associated with a query name, -- * The application uses the `List` procedure generated by [http://code.google.com/p/ada-gen Dynamo]. -- -- == XML Query File and Mapping == -- === XML Query File === -- The XML query file uses the `query-mapping` root element. It should -- define at most one `class` mapping and several `query` definitions. -- The `class` definition should come first before any `query` definition. -- -- <query-mapping> -- <class>...</class> -- <query>...</query> -- </query-mapping> -- -- == SQL Result Mapping == -- The XML query mapping is very close to the database table mapping. -- The difference is that there is no need to specify and table name -- nor any SQL type. The XML query mapping is used to build an Ada -- record that correspond to query results. Unlike the database table mapping, -- the Ada record will not be tagged and its definition will expose all the record -- members directly. -- -- The following XML query mapping: -- -- <query-mapping> -- <class name='Samples.Model.User_Info'> -- <property name="name" type="String"> -- <comment>the user name</comment> -- </property> -- <property name="email" type="String"> -- <comment>the email address</comment> -- </property> -- </class> -- </query-mapping> -- -- will generate the following Ada record: -- -- package Samples.Model is -- type User_Info is record -- Name : Unbounded_String; -- Email : Unbounded_String; -- end record; -- end Samples.Model; -- -- The same query mapping can be used by different queries. -- -- === SQL Queries === -- The XML query file defines a list of SQL queries that the application -- can use. Each query is associated with a unique name. The application -- will use that name to identify the SQL query to execute. For each query, -- the file also describes the SQL query pattern that must be used for -- the query execution. -- -- <query name='xxx' class='Samples.Model.User_Info'> -- <sql driver='mysql'> -- select u.name, u.email from user -- </sql> -- <sql driver='sqlite'> -- ... -- </sql> -- <sql-count driver='mysql'> -- select count(*) from user u -- </sql-count> -- </query> -- -- The query contains basically two SQL patterns. The `sql` element represents -- the main SQL pattern. This is the SQL that is used by the `List` operation. -- In some cases, the result set returned by the query is limited to return only -- a maximum number of rows. This is often use in paginated lists. -- -- The `sql-count` element represents an SQL query to indicate the total number -- of elements if the SQL query was not limited. package ADO.Queries is type Query_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Info is limited private; type Query_Info_Access is access all Query_Info; type Query_Info_Ref_Access is private; type Query_Manager (Query_Count : Query_Index; File_Count : File_Index) is limited private; type Query_Manager_Access is access all Query_Manager; Null_Query_Info_Ref : constant Query_Info_Ref_Access; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Manager : in Query_Manager_Access) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager_Access; Use_Count : in Boolean) return String; private -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). -- Query : Query_Info_Ref_Access; Query : Query_Index := 0; end record; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.String_Access; -- File File : Query_File_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Atomic_Ref; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type Query_Manager (Query_Count : Query_Index; File_Count : File_Index) is limited record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table (1 .. Query_Count); Files : File_Table (1 .. File_Count); end record; Null_Query_Info_Ref : constant Query_Info_Ref_Access := null; end ADO.Queries;
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == Introduction == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application. -- The benefit of the framework are the following: -- -- * The SQL query result are directly mapped in Ada records, -- * It is easy to change or tune an SQL query without re-building the application, -- * The SQL query can be easily tuned for a given database -- -- The database query framework uses an XML query file: -- -- * The XML query file defines a mapping that represents the result of SQL queries, -- * The XML mapping is used by [http://code.google.com/p/ada-gen Dynamo] to generate an Ada record, -- * The XML query file also defines a set of SQL queries, each query being identified by a unique name, -- * The XML query file is read by the application to obtain the SQL query associated with a query name, -- * The application uses the `List` procedure generated by [http://code.google.com/p/ada-gen Dynamo]. -- -- == XML Query File and Mapping == -- === XML Query File === -- The XML query file uses the `query-mapping` root element. It should -- define at most one `class` mapping and several `query` definitions. -- The `class` definition should come first before any `query` definition. -- -- <query-mapping> -- <class>...</class> -- <query>...</query> -- </query-mapping> -- -- == SQL Result Mapping == -- The XML query mapping is very close to the database table mapping. -- The difference is that there is no need to specify and table name -- nor any SQL type. The XML query mapping is used to build an Ada -- record that correspond to query results. Unlike the database table mapping, -- the Ada record will not be tagged and its definition will expose all the record -- members directly. -- -- The following XML query mapping: -- -- <query-mapping> -- <class name='Samples.Model.User_Info'> -- <property name="name" type="String"> -- <comment>the user name</comment> -- </property> -- <property name="email" type="String"> -- <comment>the email address</comment> -- </property> -- </class> -- </query-mapping> -- -- will generate the following Ada record: -- -- package Samples.Model is -- type User_Info is record -- Name : Unbounded_String; -- Email : Unbounded_String; -- end record; -- end Samples.Model; -- -- The same query mapping can be used by different queries. -- -- === SQL Queries === -- The XML query file defines a list of SQL queries that the application -- can use. Each query is associated with a unique name. The application -- will use that name to identify the SQL query to execute. For each query, -- the file also describes the SQL query pattern that must be used for -- the query execution. -- -- <query name='xxx' class='Samples.Model.User_Info'> -- <sql driver='mysql'> -- select u.name, u.email from user -- </sql> -- <sql driver='sqlite'> -- ... -- </sql> -- <sql-count driver='mysql'> -- select count(*) from user u -- </sql-count> -- </query> -- -- The query contains basically two SQL patterns. The `sql` element represents -- the main SQL pattern. This is the SQL that is used by the `List` operation. -- In some cases, the result set returned by the query is limited to return only -- a maximum number of rows. This is often use in paginated lists. -- -- The `sql-count` element represents an SQL query to indicate the total number -- of elements if the SQL query was not limited. package ADO.Queries is type Query_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Info is limited private; type Query_Info_Access is access all Query_Info; type Query_Info_Ref_Access is private; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with private; type Query_Manager_Access is access all Query_Manager; Null_Query_Info_Ref : constant Query_Info_Ref_Access; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Manager : in Query_Manager'Class) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String; private -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). -- Query : Query_Info_Ref_Access; Query : Query_Index := 0; end record; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.String_Access; -- File File : Query_File_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Atomic_Ref; type Query_Table_Access is access all Query_Table; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type File_Table_Access is access all File_Table; -- -- type Query_Manager (Query_Count : Query_Index; -- File_Count : File_Index) is limited record -- Driver : ADO.Drivers.Driver_Index; -- Queries : Query_Table (1 .. Query_Count); -- Files : File_Table (1 .. File_Count); -- end record; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table_Access; Files : File_Table_Access; end record; overriding procedure Finalize (Manager : in out Query_Manager); Null_Query_Info_Ref : constant Query_Info_Ref_Access := null; end ADO.Queries;
Change Query_Manager to better take care of memory and simplify the operations
Change Query_Manager to better take care of memory and simplify the operations
Ada
apache-2.0
stcarrez/ada-ado
e5a1fa019bf652d166547eff0551da22ab3d5e96
src/gen-model-tables.adb
src/gen-model-tables.adb
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; package body Gen.Model.Tables is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" and From.Type_Mapping /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Type_Mapping.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; Name : constant String := To_String (From.Type_Name); begin if From.Type_Mapping /= null then return From.Type_Mapping.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if From.Type_Mapping /= null then return To_String (From.Type_Mapping.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is begin O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); if Length (O.Sql_Type) = 0 then end if; end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; package body Gen.Model.Tables is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" and From.Type_Mapping /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Type_Mapping.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; Name : constant String := To_String (From.Type_Name); begin if From.Type_Mapping /= null then return From.Type_Mapping.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if From.Type_Mapping /= null then return To_String (From.Type_Mapping.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is begin O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
Fix compilation
Fix compilation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
82ff82fea2f51c5e52e1cc744b49c5e75f999259
awa/src/awa-audits-services.ads
awa/src/awa-audits-services.ads
----------------------------------------------------------------------- -- awa-audits-services -- AWA Audit Manager -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Audits; with ADO.Sessions; package AWA.Audits.Services is -- ------------------------------ -- Event manager -- ------------------------------ -- The <b>Event_Manager</b> manages the dispatch of event to the right event queue -- or to the event action. The event manager holds a list of actions that must be -- triggered for a particular event/queue pair. Such list is created and initialized -- when the application is configured. It never changes. type Audit_Manager is limited new ADO.Audits.Audit_Manager with null record; type Audit_Manager_Access is access all Audit_Manager'Class; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in ADO.Audits.Auditable_Object_Record'Class; Changes : in ADO.Audits.Audit_Array); end AWA.Audits.Services;
----------------------------------------------------------------------- -- awa-audits-services -- AWA Audit Manager -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with ADO.Audits; with ADO.Sessions; package AWA.Audits.Services is -- ------------------------------ -- Event manager -- ------------------------------ -- The <b>Event_Manager</b> manages the dispatch of event to the right event queue -- or to the event action. The event manager holds a list of actions that must be -- triggered for a particular event/queue pair. Such list is created and initialized -- when the application is configured. It never changes. type Audit_Manager is limited new ADO.Audits.Audit_Manager with private; type Audit_Manager_Access is access all Audit_Manager'Class; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in ADO.Audits.Auditable_Object_Record'Class; Changes : in ADO.Audits.Audit_Array); -- Find the audit field identification number from the entity type and field name. function Get_Audit_Field (Manager : in Audit_Manager; Name : in String; Entity : in ADO.Entity_Type) return ADO.Identifier; private type Field_Key (Len : Natural) is record Entity : ADO.Entity_Type; Name : String (1 .. Len); end record; function Hash (Item : in Field_Key) return Ada.Containers.Hash_Type; package Audit_Field_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Field_Key, Element_Type => ADO.Identifier, Hash => Hash, Equivalent_Keys => "=", "=" => ADO."="); type Audit_Manager is limited new ADO.Audits.Audit_Manager with record Fields : Audit_Field_Maps.Map; end record; end AWA.Audits.Services;
Add audit field support in the model: - Declare Get_Audit_Field function - Declare Field_Key record - Instantiate Audit_Fields_Maps package - Keep a map of audited field to the audit field unique id
Add audit field support in the model: - Declare Get_Audit_Field function - Declare Field_Key record - Instantiate Audit_Fields_Maps package - Keep a map of audited field to the audit field unique id
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5fbb186e4788e480318e4d227f1a73eeca759323
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 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 Glfw.Errors; with Glfw.Windows.Context; with Glfw.Windows.Hints; with Orka.Inputs.GLFW; with Orka.Logging; package body Orka.Windows.GLFW is use Orka.Logging; package Messages is new Orka.Logging.Messages (Other); procedure Print_Error (Code : Standard.Glfw.Errors.Kind; Description : String) is begin Messages.Insert (Error, "GLFW " & Code'Image & ": " & Trim (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 Messages.Insert (Debug, "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;
Use Orka.Logging in GLFW error callback
orka: Use Orka.Logging in GLFW error callback Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
28a5eb3dc82ff38f0aa64a6691505c8263eb02f4
tools/druss-commands.ads
tools/druss-commands.ads
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Util.Properties; with Druss.Gateways; package Druss.Commands is type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; end record; package Drivers is new Util.Commands.Drivers (Context_Type => Context_Type, Driver_Name => "druss-drivers"); subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; procedure Initialize; end Druss.Commands;
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Druss.Gateways; package Druss.Commands is type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; end record; package Drivers is new Util.Commands.Drivers (Context_Type => Context_Type, Driver_Name => "druss-drivers"); subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; procedure Initialize; end Druss.Commands;
Remove unused with clause
Remove unused with clause
Ada
apache-2.0
stcarrez/bbox-ada-api
20695d06cba9c725cc03711bb19ea15b28337362
src/ado-sequences.ads
src/ado-sequences.ads
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with ADO.Sessions; with ADO.Objects; limited with ADO.Sessions.Factory; -- == Sequence Generators == -- The sequence generator is responsible for creating unique ID's -- across all database objects. -- -- Each table can be associated with a sequence generator. -- The sequence factory is shared by several sessions and the -- implementation is thread-safe. -- -- The HiLoGenerator implements a simple High Low sequence generator -- by using sequences that avoid to access the database. -- -- Example: -- -- F : Factory; -- Id : Identifier; -- -- Allocate (Manager => F, Name => "user", Id => Id); -- -- @include ado-sequences-hilo.ads package ADO.Sequences is type Session_Factory_Access is access all ADO.Sessions.Factory.Session_Factory'Class; -- ------------------------------ -- Abstract sequence generator -- ------------------------------ type Generator is abstract new Ada.Finalization.Limited_Controlled with private; type Generator_Access is access all Generator'Class; -- Get the name of the sequence. function Get_Sequence_Name (Gen : in Generator'Class) return String; -- Allocate an identifier using the generator. procedure Allocate (Gen : in out Generator; Id : in out Objects.Object_Record'Class) is abstract; -- Get a session to connect to the database. function Get_Session (Gen : in Generator) return ADO.Sessions.Master_Session'Class; type Generator_Factory is access function (Sess_Factory : in Session_Factory_Access) return Generator_Access; -- ------------------------------ -- Sequence factory -- ------------------------------ -- The sequence <b>Factory</b> allocates unique ids for new objects. -- The factory is shared by all connections to the same database. type Factory is limited private; type Factory_Access is access all Factory; -- Allocate a unique identifier for the given sequence. procedure Allocate (Manager : in out Factory; Id : in out Objects.Object_Record'Class); -- Set a generator to be used for the given sequence. procedure Set_Generator (Manager : in out Factory; Name : in String; Gen : in Generator_Access); -- Set the default factory for creating generators. -- The default factory is the HiLo generator. procedure Set_Default_Generator (Manager : in out Factory; Factory : in Generator_Factory; Sess_Factory : in Session_Factory_Access); private use Ada.Strings.Unbounded; type Generator is abstract new Ada.Finalization.Limited_Controlled with record Name : Unbounded_String; Factory : Session_Factory_Access; end record; -- Each sequence generator is accessed through a protected type -- to make sure the allocation is unique and works in multi-threaded -- environments. protected type Sequence_Generator is -- Allocate a unique identifier for the given sequence. procedure Allocate (Id : in out Objects.Object_Record'Class); procedure Set_Generator (Name : in Unbounded_String; Gen : in Generator_Access); -- Free the generator procedure Clear; private Generator : Generator_Access; end Sequence_Generator; type Sequence_Generator_Access is access all Sequence_Generator; -- Map to keep track of allocation generators for each sequence. package Sequence_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Sequence_Generator_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => "="); -- The sequence factory map is also accessed through a protected type. protected type Factory_Map is -- Get the sequence generator associated with the name. -- If there is no such generator, an entry is created by using -- the default generator. procedure Get_Generator (Name : in Unbounded_String; Gen : out Sequence_Generator_Access); -- Set the sequence generator associated with the name. procedure Set_Generator (Name : in Unbounded_String; Gen : in Sequence_Generator_Access); -- Set the default sequence generator. procedure Set_Default_Generator (Gen : in Generator_Factory; Factory : in Session_Factory_Access); -- Clear the factory map. procedure Clear; private Map : Sequence_Maps.Map; Create_Generator : Generator_Factory; Sess_Factory : Session_Factory_Access; end Factory_Map; type Factory is new Ada.Finalization.Limited_Controlled with record Map : Factory_Map; end record; overriding procedure Finalize (Manager : in out Factory); end ADO.Sequences;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with ADO.Sessions; with ADO.Objects; limited with ADO.Sessions.Factory; -- == Sequence Generators == -- The sequence generator is responsible for creating unique ID's -- across all database objects. -- -- Each table can be associated with a sequence generator. -- The sequence factory is shared by several sessions and the -- implementation is thread-safe. -- -- The `HiLoGenerator` implements a simple High Low sequence generator -- by using sequences that avoid to access the database. -- -- Example: -- -- F : Factory; -- Id : Identifier; -- ... -- Allocate (Manager => F, Name => "user", Id => Id); -- -- @include ado-sequences-hilo.ads package ADO.Sequences is type Session_Factory_Access is access all ADO.Sessions.Factory.Session_Factory'Class; -- ------------------------------ -- Abstract sequence generator -- ------------------------------ type Generator is abstract new Ada.Finalization.Limited_Controlled with private; type Generator_Access is access all Generator'Class; -- Get the name of the sequence. function Get_Sequence_Name (Gen : in Generator'Class) return String; -- Allocate an identifier using the generator. procedure Allocate (Gen : in out Generator; Id : in out Objects.Object_Record'Class) is abstract; -- Get a session to connect to the database. function Get_Session (Gen : in Generator) return ADO.Sessions.Master_Session'Class; type Generator_Factory is access function (Sess_Factory : in Session_Factory_Access) return Generator_Access; -- ------------------------------ -- Sequence factory -- ------------------------------ -- The sequence <b>Factory</b> allocates unique ids for new objects. -- The factory is shared by all connections to the same database. type Factory is limited private; type Factory_Access is access all Factory; -- Allocate a unique identifier for the given sequence. procedure Allocate (Manager : in out Factory; Id : in out Objects.Object_Record'Class); -- Set a generator to be used for the given sequence. procedure Set_Generator (Manager : in out Factory; Name : in String; Gen : in Generator_Access); -- Set the default factory for creating generators. -- The default factory is the HiLo generator. procedure Set_Default_Generator (Manager : in out Factory; Factory : in Generator_Factory; Sess_Factory : in Session_Factory_Access); private use Ada.Strings.Unbounded; type Generator is abstract new Ada.Finalization.Limited_Controlled with record Name : Unbounded_String; Factory : Session_Factory_Access; end record; -- Each sequence generator is accessed through a protected type -- to make sure the allocation is unique and works in multi-threaded -- environments. protected type Sequence_Generator is -- Allocate a unique identifier for the given sequence. procedure Allocate (Id : in out Objects.Object_Record'Class); procedure Set_Generator (Name : in Unbounded_String; Gen : in Generator_Access); -- Free the generator procedure Clear; private Generator : Generator_Access; end Sequence_Generator; type Sequence_Generator_Access is access all Sequence_Generator; -- Map to keep track of allocation generators for each sequence. package Sequence_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Sequence_Generator_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => "="); -- The sequence factory map is also accessed through a protected type. protected type Factory_Map is -- Get the sequence generator associated with the name. -- If there is no such generator, an entry is created by using -- the default generator. procedure Get_Generator (Name : in Unbounded_String; Gen : out Sequence_Generator_Access); -- Set the sequence generator associated with the name. procedure Set_Generator (Name : in Unbounded_String; Gen : in Sequence_Generator_Access); -- Set the default sequence generator. procedure Set_Default_Generator (Gen : in Generator_Factory; Factory : in Session_Factory_Access); -- Clear the factory map. procedure Clear; private Map : Sequence_Maps.Map; Create_Generator : Generator_Factory; Sess_Factory : Session_Factory_Access; end Factory_Map; type Factory is new Ada.Finalization.Limited_Controlled with record Map : Factory_Map; end record; overriding procedure Finalize (Manager : in out Factory); end ADO.Sequences;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-ado
45ef44d63ec49af83778470dd67da4b175bb182f
src/base/os-unix/util-systems-os.ads
src/base/os-unix/util-systems-os.ads
----------------------------------------------------------------------- -- util-systems-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 2017, 2018, 2019, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.LF; use Util.Systems.Constants; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; type Process_Identifier is new Integer; subtype File_Type is Util.Systems.Types.File_Type; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened use type Util.Systems.Types.File_Type; -- This use clause is required by GNAT 2018 for the -1! NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "read"; function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "write"; -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer) with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "exit"; -- Fork a new process function Sys_Fork return Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Fork a new process (vfork implementation) function Sys_VFork return Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "execvp"; -- Execute a process with the given arguments. function Sys_Execve (File : in Ptr; Args : in Ptr_Array; Envp : in Ptr_Array) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "execve"; -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "waitpid"; -- Get the current process identification. function Sys_Getpid return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "getpid"; -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "pipe"; -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "dup2"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "open"; -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fcntl"; function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "kill"; function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.STAT_NAME; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.FSTAT_NAME; function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "lseek"; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "ftruncate"; function Sys_Truncate (Path : in Ptr; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "truncate"; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fchmod"; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chmod"; -- Change working directory. function Sys_Chdir (Path : in Ptr) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chdir"; -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in String; Newpath : in String) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "rename"; function Sys_Unlink (Path : in String) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "unlink"; -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "__get_errno"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "strerror"; type DIR is new System.Address; Null_Dir : constant DIR := DIR (System.Null_Address); -- Equivalent to Posix opendir (3) but handles some portability issues. -- We could use opendir, readdir_r and closedir but the __gnat_* alternative -- solves function Opendir (Directory : in String) return DIR with Import, External_Name => "__gnat_opendir", Convention => C; function Readdir (Directory : in DIR; Buffer : in System.Address; Last : not null access Integer) return System.Address with Import, External_Name => "__gnat_readdir", Convention => C; function Closedir (Directory : in DIR) return Integer with Import, External_Name => "__gnat_closedir", Convention => C; end Util.Systems.Os;
----------------------------------------------------------------------- -- util-systems-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 2017, 2018, 2019, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.LF; use Util.Systems.Constants; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; type Process_Identifier is new Integer; subtype File_Type is Util.Systems.Types.File_Type; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened use type Util.Systems.Types.File_Type; -- This use clause is required by GNAT 2018 for the -1! NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "read"; function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "write"; -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer) with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "exit"; -- Fork a new process function Sys_Fork return Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Fork a new process (vfork implementation) function Sys_VFork return Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "execvp"; -- Execute a process with the given arguments. function Sys_Execve (File : in Ptr; Args : in Ptr_Array; Envp : in Ptr_Array) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "execve"; -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "waitpid"; -- Get the current process identification. function Sys_Getpid return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "getpid"; -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "pipe"; -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "dup2"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "open"; -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fcntl"; function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "kill"; function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.STAT_NAME; function Sys_Lstat (Path : in String; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.LSTAT_NAME; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.FSTAT_NAME; function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "lseek"; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "ftruncate"; function Sys_Truncate (Path : in Ptr; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "truncate"; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fchmod"; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chmod"; -- Change working directory. function Sys_Chdir (Path : in Ptr) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chdir"; -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in String; Newpath : in String) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "rename"; function Sys_Unlink (Path : in String) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "unlink"; -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "__get_errno"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "strerror"; type DIR is new System.Address; Null_Dir : constant DIR := DIR (System.Null_Address); -- Equivalent to Posix opendir (3) but handles some portability issues. -- We could use opendir, readdir_r and closedir but the __gnat_* alternative -- solves function Opendir (Directory : in String) return DIR with Import, External_Name => "__gnat_opendir", Convention => C; function Readdir (Directory : in DIR; Buffer : in System.Address; Last : not null access Integer) return System.Address with Import, External_Name => "__gnat_readdir", Convention => C; function Closedir (Directory : in DIR) return Integer with Import, External_Name => "__gnat_closedir", Convention => C; end Util.Systems.Os;
Declare Sys_Lstat function
Declare Sys_Lstat function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2f545c92ee9dbd46ea8f55ed3c58d8da0e6853ee
src/security-oauth-file_registry.ads
src/security-oauth-file_registry.ads
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.OAuth.Servers; private with Util.Strings.Maps; private with Security.Random; package Security.OAuth.File_Registry is type File_Principal is new Security.Principal with private; type File_Principal_Access is access all File_Principal'Class; -- Get the principal name. overriding function Get_Name (From : in File_Principal) return String; type File_Application_Manager is new Servers.Application_Manager with private; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class; -- Add the application to the application repository. procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application); type File_Realm_Manager is limited new Servers.Realm_Manager with private; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean); -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access); overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access); overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access); -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String; -- Add a username with the associated password. procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String); private use Ada.Strings.Unbounded; package Application_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Servers.Application, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => Servers."="); package Token_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Principal_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); package User_Maps renames Util.Strings.Maps; type File_Principal is new Security.Principal with record Token : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type File_Application_Manager is new Servers.Application_Manager with record Applications : Application_Maps.Map; end record; type File_Realm_Manager is limited new Servers.Realm_Manager with record Users : User_Maps.Map; Tokens : Token_Maps.Map; Random : Security.Random.Generator; Token_Bits : Positive := 256; end record; end Security.OAuth.File_Registry;
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- 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 Ada.Strings.Unbounded; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Util.Properties; with Security.OAuth.Servers; private with Util.Strings.Maps; private with Security.Random; package Security.OAuth.File_Registry is type File_Principal is new Security.Principal with private; type File_Principal_Access is access all File_Principal'Class; -- Get the principal name. overriding function Get_Name (From : in File_Principal) return String; type File_Application_Manager is new Servers.Application_Manager with private; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class; -- Add the application to the application repository. procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application); -- Load from the properties the definition of applications. The list of applications -- is controled by the property <prefix>.list which contains a comma separated list of -- application names or ids. The application definition are represented by properties -- of the form: -- <prefix>.<app>.client_id -- <prefix>.<app>.client_secret -- <prefix>.<app>.callback_url procedure Load (Realm : in out File_Application_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String); procedure Load (Realm : in out File_Application_Manager; Path : in String; Prefix : in String); type File_Realm_Manager is limited new Servers.Realm_Manager with private; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean); -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access); overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access); overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access); -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String; -- Add a username with the associated password. procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String); private use Ada.Strings.Unbounded; package Application_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Servers.Application, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => Servers."="); package Token_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Principal_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); package User_Maps renames Util.Strings.Maps; type File_Principal is new Security.Principal with record Token : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type File_Application_Manager is new Servers.Application_Manager with record Applications : Application_Maps.Map; end record; type File_Realm_Manager is limited new Servers.Realm_Manager with record Users : User_Maps.Map; Tokens : Token_Maps.Map; Random : Security.Random.Generator; Token_Bits : Positive := 256; end record; end Security.OAuth.File_Registry;
Declare Load procedure on File_Application_Manager to load some definitions of applications
Declare Load procedure on File_Application_Manager to load some definitions of applications
Ada
apache-2.0
stcarrez/ada-security
1618a356752128d31ddee4db795a738f36da5766
src/asf-views-facelets.ads
src/asf-views-facelets.ads
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Factory; with ASF.Components.Base; with Util.Strings.Maps; with Ada.Finalization; -- The <b>ASF.Views.Facelets</b> package contains the facelet factory -- responsible for getting the facelet tree from a facelet name. -- The facelets (or *.xhtml) files are loaded by the reader to form -- a tag node tree which is cached by the factory. The facelet factory -- is shared by multiple requests and threads. package ASF.Views.Facelets is type Facelet is private; type Facelet_Access is access all Facelet; -- Returns True if the facelet is null/empty. function Is_Null (F : Facelet) return Boolean; -- ------------------------------ -- Facelet factory -- ------------------------------ -- The facelet factory allows to retrieve the node tree to build the -- component tree. The node tree can be shared by several component trees. -- The node tree is initialized from the <b>XHTML</b> view file. It is put -- in a cache to avoid loading and parsing the file several times. type Facelet_Factory is limited private; -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Create the component tree from the facelet view. procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access); -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean); -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String; -- Register a module and directory where the module files are stored. procedure Register_Module (Factory : in out Facelet_Factory; Name : in String; Paths : in String); -- Clear the facelet cache procedure Clear_Cache (Factory : in out Facelet_Factory); private use Ada.Strings.Unbounded; type Facelet is record Root : ASF.Views.Nodes.Tag_Node_Access; Path : Unbounded_String; File : ASF.Views.File_Info_Access; Modify_Time : Ada.Calendar.Time; end record; -- Tag library map indexed on the library namespace. package Facelet_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Facelet, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); use Facelet_Maps; -- Lock for accessing the shared cache protected type RW_Lock is entry Read; procedure Release_Read; entry Write; procedure Release_Write; private Readable : Boolean := True; Reader_Count : Natural := 0; end RW_Lock; type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record Paths : Unbounded_String := To_Unbounded_String (""); Lock : RW_Lock; Map : Facelet_Maps.Map; Path_Map : Util.Strings.Maps.Map; -- The component factory Factory : access ASF.Factory.Component_Factory; -- Whether the unknown tags are escaped using XML escape rules. Escape_Unknown_Tags : Boolean := True; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; -- Free the storage held by the factory cache. overriding procedure Finalize (Factory : in out Facelet_Factory); end ASF.Views.Facelets;
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010, 2011, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Factory; with ASF.Components.Base; with Util.Strings.Maps; with Ada.Finalization; -- The <b>ASF.Views.Facelets</b> package contains the facelet factory -- responsible for getting the facelet tree from a facelet name. -- The facelets (or *.xhtml) files are loaded by the reader to form -- a tag node tree which is cached by the factory. The facelet factory -- is shared by multiple requests and threads. package ASF.Views.Facelets is type Facelet is private; type Facelet_Access is access all Facelet; -- Returns True if the facelet is null/empty. function Is_Null (F : Facelet) return Boolean; -- ------------------------------ -- Facelet factory -- ------------------------------ -- The facelet factory allows to retrieve the node tree to build the -- component tree. The node tree can be shared by several component trees. -- The node tree is initialized from the <b>XHTML</b> view file. It is put -- in a cache to avoid loading and parsing the file several times. type Facelet_Factory is limited private; -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Create the component tree from the facelet view. procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access); -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean); -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String; -- Register a module and directory where the module files are stored. procedure Register_Module (Factory : in out Facelet_Factory; Name : in String; Paths : in String); -- Clear the facelet cache procedure Clear_Cache (Factory : in out Facelet_Factory); private use Ada.Strings.Unbounded; type Facelet is record Root : ASF.Views.Nodes.Tag_Node_Access; File : ASF.Views.File_Info_Access; Modify_Time : Ada.Calendar.Time; end record; -- Tag library map indexed on the library namespace. package Facelet_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Facelet, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); use Facelet_Maps; -- Lock for accessing the shared cache protected type RW_Lock is entry Read; procedure Release_Read; entry Write; procedure Release_Write; private Readable : Boolean := True; Reader_Count : Natural := 0; end RW_Lock; type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record Paths : Unbounded_String := To_Unbounded_String (""); Lock : RW_Lock; Map : Facelet_Maps.Map; Path_Map : Util.Strings.Maps.Map; -- The component factory Factory : access ASF.Factory.Component_Factory; -- Whether the unknown tags are escaped using XML escape rules. Escape_Unknown_Tags : Boolean := True; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; -- Free the storage held by the factory cache. overriding procedure Finalize (Factory : in out Facelet_Factory); end ASF.Views.Facelets;
Remove the Path member from the Factelet because this is not used
Remove the Path member from the Factelet because this is not used
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
893ca11c1943e84f7a9b8ade1f930bf0459d0bbc
awa/plugins/awa-comments/src/awa-comments-beans.adb
awa/plugins/awa-comments/src/awa-comments-beans.adb
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- 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 ADO.Sessions.Entities; with ADO.Queries; with ADO.Statements; package body AWA.Comments.Beans is -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) with which the comments are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a comment on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; Session : in ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Comments.Models.Query_Comment_List); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; while Stmt.Has_Elements loop Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); Stmt.Next; end loop; end; end Load_Comments; -- ------------------------------ -- Create the comment list bean instance. -- ------------------------------ function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_List_Bean_Access := new Comment_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_List_Bean; end AWA.Comments.Beans;
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- 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 ADO.Sessions.Entities; with ADO.Queries; with ADO.Statements; with ADO.Utils; with AWA.Services.Contexts; package body AWA.Comments.Beans is package ASC renames AWA.Services.Contexts; -- Get the value identified by the name. overriding function Get_Value (From : in Comment_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name); end if; end Get_Value; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "comment" then From.Set_Message (Util.Beans.Objects.To_String (Value)); elsif Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "status" then From.Set_Status (AWA.Comments.Models.Status_Type_Objects.To_Value (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Module.Load_Comment (From, Id); end; end if; end Set_Value; -- Create the comment. overriding procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Create_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean); end Create; -- Save the comment. overriding procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Save; -- Delete the comment. overriding procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create a new comment bean instance. -- ------------------------------ function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_Bean_Access := new Comment_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) with which the comments are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a comment on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; Session : in ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Comments.Models.Query_Comment_List); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; while Stmt.Has_Elements loop Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); Stmt.Next; end loop; end; end Load_Comments; -- ------------------------------ -- Create the comment list bean instance. -- ------------------------------ function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_List_Bean_Access := new Comment_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_List_Bean; end AWA.Comments.Beans;
Implement the Comment_Bean with the create operation
Implement the Comment_Bean with the create operation
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
a6e7d9be3f2e3dbdd05f8370b07fd7cbb5805010
asfunit/asf-tests.ads
asfunit/asf-tests.ads
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Server; with ASF.Applications.Main; with Util.Tests; with GNAT.Source_Info; -- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test -- on top of ASF. package ASF.Tests is -- Initialize the asf test framework mockup. If the application is not specified, -- a default ASF application is created. procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Get the server function Get_Server return access ASF.Server.Container; -- Get the test application. function Get_Application return ASF.Applications.Main.Application_Access; -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a raw request. The URI and method must have been set on the Request object. procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response); -- Check that the response body contains the string procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body matches the regular expression procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body is a redirect to the given URI. procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); end ASF.Tests;
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Server; with ASF.Applications.Main; with Util.Tests; with EL.Contexts.Default; with EL.Variables; with GNAT.Source_Info; -- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test -- on top of ASF. package ASF.Tests is -- Initialize the asf test framework mockup. If the application is not specified, -- a default ASF application is created. procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Get the server function Get_Server return access ASF.Server.Container; -- Get the test application. function Get_Application return ASF.Applications.Main.Application_Access; -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a raw request. The URI and method must have been set on the Request object. procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response); -- Check that the response body contains the string procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body matches the regular expression procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body is a redirect to the given URI. procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); type EL_Test is new Util.Tests.Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. ELContext : EL.Contexts.Default.Default_Context_Access; Variables : EL.Variables.Variable_Mapper_Access; Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out EL_Test); -- Setup the test instance. overriding procedure Set_Up (T : in out EL_Test); end ASF.Tests;
Declare the EL_Test test support with the Set_Up and Tear_Down procedures
Declare the EL_Test test support with the Set_Up and Tear_Down procedures
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8cc63278557dc7f77881235921330431ec26070a
src/sys/serialize/xml/util-serialize-io-xml.ads
src/sys/serialize/xml/util-serialize-io-xml.ads
----------------------------------------------------------------------- -- util-serialize-io-xml -- XML Serialization Driver -- Copyright (C) 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sax.Exceptions; with Sax.Locators; with Sax.Readers; with Sax.Attributes; with Unicode.CES; with Input_Sources; with Ada.Streams; with Ada.Strings.Unbounded; with Util.Streams.Buffered; with Util.Streams.Texts; package Util.Serialize.IO.XML is Parse_Error : exception; type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class; Sink : in out Reader'Class); -- Set the XHTML reader to ignore or not the white spaces. -- When set to True, the ignorable white spaces will not be kept. procedure Set_Ignore_White_Spaces (Reader : in out Parser; Value : in Boolean); -- Set the XHTML reader to ignore empty lines. procedure Set_Ignore_Empty_Lines (Reader : in out Parser; Value : in Boolean); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; type Xhtml_Reader is new Sax.Readers.Reader with private; -- ------------------------------ -- XML Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating an XML output stream. -- The stream object takes care of the XML escape rules. type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private; -- Set the target output stream. procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access); -- Flush the buffer (if any) to the sink. overriding procedure Flush (Stream : in out Output_Stream); -- Close the sink. overriding procedure Close (Stream : in out Output_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Write a raw character on the stream. procedure Write (Stream : in out Output_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream; Item : in String); -- Write a character on the response stream and escape that character as necessary. procedure Write_Escape (Stream : in out Output_Stream'Class; Char : in Wide_Wide_Character); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new XML object. procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current XML object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a XML name/value attribute. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Write a XML name/value entity (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String); -- Starts a XML array. overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a XML array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); -- Return the location where the exception was raised. function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class) return String; private overriding procedure Warning (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator); overriding procedure Start_Document (Handler : in out Xhtml_Reader); overriding procedure End_Document (Handler : in out Xhtml_Reader); overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence); overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence); overriding procedure Start_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""; Atts : in Sax.Attributes.Attributes'Class); overriding procedure End_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""); overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence); overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence); overriding procedure Start_Cdata (Handler : in out Xhtml_Reader); overriding procedure End_Cdata (Handler : in out Xhtml_Reader); overriding function Resolve_Entity (Handler : Xhtml_Reader; Public_Id : Unicode.CES.Byte_Sequence; System_Id : Unicode.CES.Byte_Sequence) return Input_Sources.Input_Source_Access; overriding procedure Start_DTD (Handler : in out Xhtml_Reader; Name : Unicode.CES.Byte_Sequence; Public_Id : Unicode.CES.Byte_Sequence := ""; System_Id : Unicode.CES.Byte_Sequence := ""); procedure Collect_Text (Handler : in out Xhtml_Reader; Content : Unicode.CES.Byte_Sequence); type Xhtml_Reader is new Sax.Readers.Reader with record Stack_Pos : Natural := 0; Handler : access Parser'Class; Text : Ada.Strings.Unbounded.Unbounded_String; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; Sink : access Reader'Class; end record; type Parser is new Util.Serialize.IO.Parser with record -- The SAX locator to find the current file and line number. Locator : Sax.Locators.Locator; Has_Pending_Char : Boolean := False; Pending_Char : Character; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Close_Start : Boolean := False; Stream : Util.Streams.Texts.Print_Stream_Access; end record; end Util.Serialize.IO.XML;
----------------------------------------------------------------------- -- util-serialize-io-xml -- XML Serialization Driver -- Copyright (C) 2011, 2012, 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sax.Exceptions; with Sax.Locators; with Sax.Readers; with Sax.Attributes; with Unicode.CES; with Input_Sources; with Ada.Streams; with Ada.Strings.Unbounded; with Util.Streams.Buffered; with Util.Streams.Texts; package Util.Serialize.IO.XML is Parse_Error : exception; type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class; Sink : in out Reader'Class); -- Set the XHTML reader to ignore or not the white spaces. -- When set to True, the ignorable white spaces will not be kept. procedure Set_Ignore_White_Spaces (Reader : in out Parser; Value : in Boolean); -- Set the XHTML reader to ignore empty lines. procedure Set_Ignore_Empty_Lines (Reader : in out Parser; Value : in Boolean); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; type Xhtml_Reader is new Sax.Readers.Reader with private; -- ------------------------------ -- XML Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating an XML output stream. -- The stream object takes care of the XML escape rules. type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private; -- Set the target output stream. procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access); -- Flush the buffer (if any) to the sink. overriding procedure Flush (Stream : in out Output_Stream); -- Close the sink. overriding procedure Close (Stream : in out Output_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Write a character on the response stream and escape that character as necessary. procedure Write_Escape (Stream : in out Output_Stream'Class; Char : in Wide_Wide_Character); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new XML object. procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current XML object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a XML name/value attribute. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Write a XML name/value entity (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String); -- Starts a XML array. overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a XML array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); -- Return the location where the exception was raised. function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class) return String; private overriding procedure Warning (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator); overriding procedure Start_Document (Handler : in out Xhtml_Reader); overriding procedure End_Document (Handler : in out Xhtml_Reader); overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence); overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence); overriding procedure Start_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""; Atts : in Sax.Attributes.Attributes'Class); overriding procedure End_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""); overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence); overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence); overriding procedure Start_Cdata (Handler : in out Xhtml_Reader); overriding procedure End_Cdata (Handler : in out Xhtml_Reader); overriding function Resolve_Entity (Handler : Xhtml_Reader; Public_Id : Unicode.CES.Byte_Sequence; System_Id : Unicode.CES.Byte_Sequence) return Input_Sources.Input_Source_Access; overriding procedure Start_DTD (Handler : in out Xhtml_Reader; Name : Unicode.CES.Byte_Sequence; Public_Id : Unicode.CES.Byte_Sequence := ""; System_Id : Unicode.CES.Byte_Sequence := ""); procedure Collect_Text (Handler : in out Xhtml_Reader; Content : Unicode.CES.Byte_Sequence); type Xhtml_Reader is new Sax.Readers.Reader with record Stack_Pos : Natural := 0; Handler : access Parser'Class; Text : Ada.Strings.Unbounded.Unbounded_String; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; Sink : access Reader'Class; end record; type Parser is new Util.Serialize.IO.Parser with record -- The SAX locator to find the current file and line number. Locator : Sax.Locators.Locator; Has_Pending_Char : Boolean := False; Pending_Char : Character; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Close_Start : Boolean := False; Stream : Util.Streams.Texts.Print_Stream_Access; end record; end Util.Serialize.IO.XML;
Remove Write and Write_Wide procedures which are provided by Util.Streams pacakge
Remove Write and Write_Wide procedures which are provided by Util.Streams pacakge
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9f445ead9ddf60d7dbaabc14325a7c739fb4c3f9
tools/druss-gateways.ads
tools/druss-gateways.ads
----------------------------------------------------------------------- -- druss-gateways -- Gateway management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Properties; with Util.Refs; with Bbox.API; package Druss.Gateways is Not_Found : exception; type State_Type is (IDLE, READY, BUSY); protected type Gateway_State is function Get_State return State_Type; private State : State_Type := IDLE; end Gateway_State; type Gateway_Type is limited new Util.Refs.Ref_Entity with record -- Gateway IP address. Ip : Ada.Strings.Unbounded.Unbounded_String; -- API password. Passwd : Ada.Strings.Unbounded.Unbounded_String; -- The Bbox serial number. Serial : Ada.Strings.Unbounded.Unbounded_String; -- Directory that contains the images. Images : Ada.Strings.Unbounded.Unbounded_String; -- The gateway state. State : Gateway_State; -- Current WAN information (from api/v1/wan). Wan : Util.Properties.Manager; -- Current LAN information (from api/v1/lan). Lan : Util.Properties.Manager; -- Wireless information (From api/v1/wireless). Wifi : Util.Properties.Manager; -- Voip information (From api/v1/voip). Voip : Util.Properties.Manager; -- Current Device information (from api/v1/device). Device : Util.Properties.Manager; -- The Bbox API client. Client : Bbox.API.Client_Type; end record; type Gateway_Type_Access is access all Gateway_Type; -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in out Gateway_Type); package Gateway_Refs is new Util.Refs.References (Element_Type => Gateway_Type, Element_Access => Gateway_Type_Access); subtype Gateway_Ref is Gateway_Refs.Ref; function "=" (Left, Right : in Gateway_Ref) return Boolean; package Gateway_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Gateway_Ref, "=" => "="); subtype Gateway_Vector is Gateway_Vectors.Vector; subtype Gateway_Cursor is Gateway_Vectors.Cursor; package Gateway_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Gateway_Ref, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- Initalize the list of gateways from the property list. procedure Initialize (Config : in Util.Properties.Manager; List : in out Gateway_Vector); -- Save the list of gateways. procedure Save_Gateways (Config : in out Util.Properties.Manager; List : in Druss.Gateways.Gateway_Vector); -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in Gateway_Ref) with pre => not Gateway.Is_Null; -- Iterate over the list of gateways and execute the <tt>Process</tt> procedure. procedure Iterate (List : in Gateway_Vector; Process : not null access procedure (G : in out Gateway_Type)); -- Find the gateway with the given IP address. function Find_IP (List : in Gateway_Vector; IP : in String) return Gateway_Ref; end Druss.Gateways;
----------------------------------------------------------------------- -- druss-gateways -- Gateway management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Properties; with Util.Refs; with Bbox.API; package Druss.Gateways is Not_Found : exception; type State_Type is (IDLE, READY, BUSY); protected type Gateway_State is function Get_State return State_Type; private State : State_Type := IDLE; end Gateway_State; type Gateway_Type is limited new Util.Refs.Ref_Entity with record -- Gateway IP address. Ip : Ada.Strings.Unbounded.Unbounded_String; -- API password. Passwd : Ada.Strings.Unbounded.Unbounded_String; -- The Bbox serial number. Serial : Ada.Strings.Unbounded.Unbounded_String; -- Directory that contains the images. Images : Ada.Strings.Unbounded.Unbounded_String; -- The gateway state. State : Gateway_State; -- Current WAN information (from api/v1/wan). Wan : Util.Properties.Manager; -- Current LAN information (from api/v1/lan). Lan : Util.Properties.Manager; -- Wireless information (From api/v1/wireless). Wifi : Util.Properties.Manager; -- Voip information (From api/v1/voip). Voip : Util.Properties.Manager; -- IPtv information (From api/v1/iptv). IPtv : Util.Properties.Manager; -- Current Device information (from api/v1/device). Device : Util.Properties.Manager; -- The Bbox API client. Client : Bbox.API.Client_Type; end record; type Gateway_Type_Access is access all Gateway_Type; -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in out Gateway_Type); package Gateway_Refs is new Util.Refs.References (Element_Type => Gateway_Type, Element_Access => Gateway_Type_Access); subtype Gateway_Ref is Gateway_Refs.Ref; function "=" (Left, Right : in Gateway_Ref) return Boolean; package Gateway_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Gateway_Ref, "=" => "="); subtype Gateway_Vector is Gateway_Vectors.Vector; subtype Gateway_Cursor is Gateway_Vectors.Cursor; package Gateway_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Gateway_Ref, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- Initalize the list of gateways from the property list. procedure Initialize (Config : in Util.Properties.Manager; List : in out Gateway_Vector); -- Save the list of gateways. procedure Save_Gateways (Config : in out Util.Properties.Manager; List : in Druss.Gateways.Gateway_Vector); -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in Gateway_Ref) with pre => not Gateway.Is_Null; -- Iterate over the list of gateways and execute the <tt>Process</tt> procedure. procedure Iterate (List : in Gateway_Vector; Process : not null access procedure (G : in out Gateway_Type)); -- Find the gateway with the given IP address. function Find_IP (List : in Gateway_Vector; IP : in String) return Gateway_Ref; end Druss.Gateways;
Add IPtv information for the gateway
Add IPtv information for the gateway
Ada
apache-2.0
stcarrez/bbox-ada-api
9b5dbfc8fd9e3c17bbfbdc4bbd4efd2d8644f516
src/ado-c.ads
src/ado-c.ads
----------------------------------------------------------------------- -- ado-c -- Support for driver implementation -- 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 Interfaces.C; with Interfaces.C.Strings; with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Unchecked_Conversion; with System; package ADO.C is type String_Ptr is limited private; -- Convert a string to a C string. function To_String_Ptr (S : String) return String_Ptr; -- Convert an unbounded string to a C string. function To_String_Ptr (S : Ada.Strings.Unbounded.Unbounded_String) return String_Ptr; -- Get the C string pointer. function To_C (S : String_Ptr) return Interfaces.C.Strings.chars_ptr; -- Set the string procedure Set_String (S : in out String_Ptr; Value : in String); function To_chars_ptr is new Ada.Unchecked_Conversion (System.Address, Interfaces.C.Strings.chars_ptr); private use Interfaces.C; type String_Ptr is new Ada.Finalization.Limited_Controlled with record Ptr : Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; end record; -- Reclaim the storage held by the C string. procedure Finalize (S : in out String_Ptr); end ADO.C;
----------------------------------------------------------------------- -- ado-c -- Support for driver implementation -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces.C; with Interfaces.C.Strings; with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Unchecked_Conversion; with System; package ADO.C is type String_Ptr is limited private; -- Convert a string to a C string. function To_String_Ptr (S : String) return String_Ptr; -- Get the C string pointer. function To_C (S : String_Ptr) return Interfaces.C.Strings.chars_ptr; -- Set the string procedure Set_String (S : in out String_Ptr; Value : in String); function To_chars_ptr is new Ada.Unchecked_Conversion (System.Address, Interfaces.C.Strings.chars_ptr); private use Interfaces.C; type String_Ptr is new Ada.Finalization.Limited_Controlled with record Ptr : Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; end record; -- Reclaim the storage held by the C string. procedure Finalize (S : in out String_Ptr); end ADO.C;
Remove unused To_String_Ptr operation
Remove unused To_String_Ptr operation
Ada
apache-2.0
stcarrez/ada-ado