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
86edaed72768bb3f434fd245913761e91fe1b28f
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- 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.Calendar; with AWA.Users.Models; with AWA.Modules.Beans; with AWA.Permissions.Services; with ADO.SQL; with Util.Log.Loggers; with AWA.Users.Modules; with AWA.Workspaces.Beans; package body AWA.Workspaces.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module"); package Register is new AWA.Modules.Beans (Module => Workspace_Module, Module_Access => Workspace_Module_Access); -- ------------------------------ -- Initialize the workspaces module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the workspaces module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Workspaces_Bean", Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Member_List_Bean", Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Invitation_Bean", Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager; -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. -- ------------------------------ procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref) is User : constant AWA.Users.Models.User_Ref := Context.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; begin if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); Workspace := AWA.Workspaces.Models.Null_Workspace; return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (Session, Query, Found); if Found then Workspace := WS; return; end if; -- Create a workspace for this user. WS.Set_Owner (User); WS.Set_Create_Date (Ada.Calendar.Clock); WS.Save (Session); -- And give full control of the workspace for this user AWA.Permissions.Services.Add_Permission (Session => Session, User => User.Get_Id, Entity => WS); Workspace := WS; end Get_Workspace; -- ------------------------------ -- Load the invitation from the access key and verify that the key is still valid. -- ------------------------------ procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is use type Ada.Calendar.Time; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.SQL.Query; DB_Key : AWA.Users.Models.Access_Key_Ref; Found : Boolean; begin Log.Debug ("Loading invitation from key {0}", Key); Query.Set_Filter ("o.access_key = :key"); Query.Bind_Param ("key", Key); DB_Key.Find (DB, Query, Found); if not Found then Log.Info ("Invitation key {0} does not exist"); raise Not_Found; end if; if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then Log.Info ("Invitation key {0} has expired"); raise Not_Found; end if; Query.Set_Filter ("o.invitee_id = :user"); Query.Bind_Param ("user", DB_Key.Get_User.Get_Id); Invitation.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn"); raise Not_Found; end if; end Load_Invitation; -- ------------------------------ -- Accept the invitation identified by the access key. -- ------------------------------ procedure Accept_Invitation (Module : in Workspace_Module; Key : in String) is use type Ada.Calendar.Time; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.SQL.Query; DB_Key : AWA.Users.Models.Access_Key_Ref; Found : Boolean; Invitation : AWA.Workspaces.Models.Invitation_Ref; begin Log.Debug ("Accept invitation with key {0}", Key); Ctx.Start; Query.Set_Filter ("o.access_key = :key"); Query.Bind_Param ("key", Key); DB_Key.Find (DB, Query, Found); if not Found then Log.Info ("Invitation key {0} does not exist"); raise Not_Found; end if; if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then Log.Info ("Invitation key {0} has expired"); raise Not_Found; end if; Query.Set_Filter ("o.invitee_id = :user"); Query.Bind_Param ("user", DB_Key.Get_User.Get_Id); Invitation.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn"); raise Not_Found; end if; DB_Key.Delete (DB); Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Invitation.Save (DB); Ctx.Commit; end Accept_Invitation; -- ------------------------------ -- Send the invitation to the user. -- ------------------------------ procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; Email : AWA.Users.Models.Email_Ref; Invitee : AWA.Users.Models.User_Ref; Invit : AWA.Workspaces.Models.Invitation_Ref; begin Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email)); Ctx.Start; if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (DB, Query, Found); if not Found then return; end if; Query.Clear; Query.Set_Filter ("o.email = ?"); Query.Add_Param (String '(Invitation.Get_Email)); Email.Find (DB, Query, Found); if not Found then Email.Set_User_Id (0); Email.Set_Email (String '(Invitation.Get_Email)); Email.Save (DB); Invitee.Set_Email (Email); Invitee.Set_Name (String '(Invitation.Get_Email)); Invitee.Save (DB); Email.Set_User_Id (Invitee.Get_Id); Email.Save (DB); else Invitee.Load (DB, Email.Get_User_Id); end if; -- Check for a previous invitation for the user and delete it. Query.Clear; Query.Set_Filter ("o.invitee_id = ? AND o.workspace_id = ?"); Query.Add_Param (Invitee.Get_Id); Query.Add_Param (WS.Get_Id); Invit.Find (DB, Query, Found); if Found then Key := AWA.Users.Models.Access_Key_Ref (Invit.Get_Access_Key); Key.Delete (DB); if not Invitation.Is_Inserted or else Invit.Get_Id /= Invitation.Get_Id then Invit.Delete (DB); end if; end if; Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key); Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB); Key.Save (DB); Invitation.Set_Access_Key (Key); Invitation.Set_Inviter (User); Invitation.Set_Invitee (Invitee); Invitation.Set_Workspace (WS); Invitation.Set_Create_Date (Ada.Calendar.Clock); Invitation.Save (DB); Ctx.Commit; end Send_Invitation; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- 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.Calendar; with AWA.Users.Models; with AWA.Modules.Beans; with AWA.Permissions.Services; with ADO.SQL; with Util.Log.Loggers; with AWA.Users.Modules; with AWA.Workspaces.Beans; package body AWA.Workspaces.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module"); package Register is new AWA.Modules.Beans (Module => Workspace_Module, Module_Access => Workspace_Module_Access); -- ------------------------------ -- Initialize the workspaces module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the workspaces module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Workspaces_Bean", Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Member_List_Bean", Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Invitation_Bean", Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager; -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. -- ------------------------------ procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref) is User : constant AWA.Users.Models.User_Ref := Context.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Member : AWA.Workspaces.Models.Workspace_Member_Ref; Query : ADO.SQL.Query; Found : Boolean; begin if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); Workspace := AWA.Workspaces.Models.Null_Workspace; return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (Session, Query, Found); if Found then Workspace := WS; return; end if; -- Create a workspace for this user. WS.Set_Owner (User); WS.Set_Create_Date (Ada.Calendar.Clock); WS.Save (Session); -- Create the member instance for this user. Member.Set_Workspace (WS); Member.Set_Member (User); Member.Set_Role ("Owner"); Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, Value => WS.Get_Create_Date)); Member.Save (Session); -- And give full control of the workspace for this user AWA.Permissions.Services.Add_Permission (Session => Session, User => User.Get_Id, Entity => WS); Workspace := WS; end Get_Workspace; -- ------------------------------ -- Load the invitation from the access key and verify that the key is still valid. -- ------------------------------ procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is use type Ada.Calendar.Time; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.SQL.Query; DB_Key : AWA.Users.Models.Access_Key_Ref; Found : Boolean; begin Log.Debug ("Loading invitation from key {0}", Key); Query.Set_Filter ("o.access_key = :key"); Query.Bind_Param ("key", Key); DB_Key.Find (DB, Query, Found); if not Found then Log.Info ("Invitation key {0} does not exist"); raise Not_Found; end if; if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then Log.Info ("Invitation key {0} has expired"); raise Not_Found; end if; Query.Set_Filter ("o.invitee_id = :user"); Query.Bind_Param ("user", DB_Key.Get_User.Get_Id); Invitation.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn"); raise Not_Found; end if; end Load_Invitation; -- ------------------------------ -- Accept the invitation identified by the access key. -- ------------------------------ procedure Accept_Invitation (Module : in Workspace_Module; Key : in String) is use type Ada.Calendar.Time; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.SQL.Query; DB_Key : AWA.Users.Models.Access_Key_Ref; Found : Boolean; Invitation : AWA.Workspaces.Models.Invitation_Ref; begin Log.Debug ("Accept invitation with key {0}", Key); Ctx.Start; Query.Set_Filter ("o.access_key = :key"); Query.Bind_Param ("key", Key); DB_Key.Find (DB, Query, Found); if not Found then Log.Info ("Invitation key {0} does not exist"); raise Not_Found; end if; if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then Log.Info ("Invitation key {0} has expired"); raise Not_Found; end if; Query.Set_Filter ("o.invitee_id = :user"); Query.Bind_Param ("user", DB_Key.Get_User.Get_Id); Invitation.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn"); raise Not_Found; end if; DB_Key.Delete (DB); Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Invitation.Save (DB); Ctx.Commit; end Accept_Invitation; -- ------------------------------ -- Send the invitation to the user. -- ------------------------------ procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; Email : AWA.Users.Models.Email_Ref; Invitee : AWA.Users.Models.User_Ref; Invit : AWA.Workspaces.Models.Invitation_Ref; Member : AWA.Workspaces.Models.Workspace_Member_Ref; begin Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email)); Ctx.Start; if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (DB, Query, Found); if not Found then return; end if; Query.Clear; Query.Set_Filter ("o.email = ?"); Query.Add_Param (String '(Invitation.Get_Email)); Email.Find (DB, Query, Found); if not Found then Email.Set_User_Id (0); Email.Set_Email (String '(Invitation.Get_Email)); Email.Save (DB); Invitee.Set_Email (Email); Invitee.Set_Name (String '(Invitation.Get_Email)); Invitee.Save (DB); Email.Set_User_Id (Invitee.Get_Id); Email.Save (DB); else Invitee.Load (DB, Email.Get_User_Id); end if; -- Create the workspace member relation. Query.Clear; Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?"); Query.Add_Param (Invitee.Get_Id); Query.Add_Param (WS.Get_Id); Member.Find (DB, Query, Found); if not Found then Member.Set_Member (Invitee); Member.Set_Workspace (WS); Member.Set_Role ("Invited"); Member.Save (DB); end if; -- Check for a previous invitation for the user and delete it. Query.Set_Filter ("o.invitee_id = ? AND o.workspace_id = ?"); Invit.Find (DB, Query, Found); if Found then Key := AWA.Users.Models.Access_Key_Ref (Invit.Get_Access_Key); Key.Delete (DB); if not Invitation.Is_Inserted or else Invit.Get_Id /= Invitation.Get_Id then Invit.Delete (DB); end if; end if; Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key); Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB); Key.Save (DB); Invitation.Set_Access_Key (Key); Invitation.Set_Inviter (User); Invitation.Set_Invitee (Invitee); Invitation.Set_Workspace (WS); Invitation.Set_Create_Date (Ada.Calendar.Clock); Invitation.Save (DB); Ctx.Commit; end Send_Invitation; end AWA.Workspaces.Modules;
Create the workspace member when a user creates the main workspace and when the invitation is created
Create the workspace member when a user creates the main workspace and when the invitation is created
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
176a345ba39309166a6e1fded21aaad3e18a5782
matp/src/events/mat-events-timelines.adb
matp/src/events/mat-events-timelines.adb
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; use type MAT.Types.Target_Size; procedure Collect (Event : in MAT.Events.Target_Event_Type); First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Prev_Event : MAT.Events.Target_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Event_Id_Type; procedure Collect (Event : in MAT.Events.Target_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > 500_000 then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.First_Event := Event; Info.Free_Size := 0; Info.Alloc_Size := 0; Prev_Event := Event; end if; Info.Last_Event := Event; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Free_Size + Event.Old_Size; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; Info.Free_Size := Info.Free_Size + Event.Size; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.First_Event := First_Event; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Target_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type); First_Id : MAT.Events.Event_Id_Type; Last_Id : MAT.Events.Event_Id_Type; First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Size); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.MSG_MALLOC and Event.Index /= MAT.Events.MSG_FREE and Event.Index /= MAT.Events.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; MAT.Events.Tools.Collect_Info (Info, Event); Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; -- ------------------------------ -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. -- ------------------------------ procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Positive; Exact : in Boolean; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Key); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for events which are selected by the filter. if not Filter.Is_Selected (Event) then return; end if; declare Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame); Key : MAT.Events.Tools.Frame_Key_Type; First : Natural; Last : Natural; begin if Exact then First := Depth; else First := Backtrace'First; end if; if Depth < Backtrace'Last then Last := Depth; else Last := Backtrace'Last; end if; for I in First .. Last loop Key.Addr := Backtrace (Backtrace'Last - I + 1); Key.Level := I; declare Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor := Frames.Find (Key); begin if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Frames.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Count := 0; MAT.Events.Tools.Collect_Info (Info, Event); Frames.Insert (Key, Info); end; end if; end; end loop; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Frames; end MAT.Events.Timelines;
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Level : in Positive; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; use type MAT.Types.Target_Size; procedure Collect (Event : in MAT.Events.Target_Event_Type); First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Prev_Event : MAT.Events.Target_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Event_Id_Type; Limit : MAT.Types.Target_Time := MAT.Types.Target_Time (Level * 1_000_000); procedure Collect (Event : in MAT.Events.Target_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > Limit then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.First_Event := Event; Info.Free_Size := 0; Info.Alloc_Size := 0; Prev_Event := Event; end if; Info.Last_Event := Event; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Free_Size + Event.Old_Size; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; Info.Free_Size := Info.Free_Size + Event.Size; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.First_Event := First_Event; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Target_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type); First_Id : MAT.Events.Event_Id_Type; Last_Id : MAT.Events.Event_Id_Type; First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Size); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.MSG_MALLOC and Event.Index /= MAT.Events.MSG_FREE and Event.Index /= MAT.Events.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; MAT.Events.Tools.Collect_Info (Info, Event); Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; -- ------------------------------ -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. -- ------------------------------ procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Positive; Exact : in Boolean; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Key); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for events which are selected by the filter. if not Filter.Is_Selected (Event) then return; end if; declare Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame); Key : MAT.Events.Tools.Frame_Key_Type; First : Natural; Last : Natural; begin if Exact then First := Depth; else First := Backtrace'First; end if; if Depth < Backtrace'Last then Last := Depth; else Last := Backtrace'Last; end if; for I in First .. Last loop Key.Addr := Backtrace (Backtrace'Last - I + 1); Key.Level := I; declare Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor := Frames.Find (Key); begin if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Frames.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Count := 0; MAT.Events.Tools.Collect_Info (Info, Event); Frames.Insert (Key, Info); end; end if; end; end loop; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Frames; end MAT.Events.Timelines;
Use the Level parameter for the Extract procedure to control the duration limit to build a new timeline
Use the Level parameter for the Extract procedure to control the duration limit to build a new timeline
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
85d9f3d1e3d66fafa241af26f6810e8430e917a9
regtests/util-streams-sockets-tests.adb
regtests/util-streams-sockets-tests.adb
----------------------------------------------------------------------- -- util-streams-sockets-tests -- Unit tests for socket streams -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.IO_Exceptions; with Util.Test_Caller; with Util.Streams.Texts; with Util.Tests.Servers; package body Util.Streams.Sockets.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Streams.Sockets"); type Test_Server is new Util.Tests.Servers.Server with record Count : Natural := 0; end record; -- Process the line received by the server. overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect", Test_Socket_Init'Access); Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write", Test_Socket_Read'Access); end Add_Tests; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is pragma Unreferenced (Stream, Client); begin if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then Into.Count := Into.Count + 1; end if; end Process_Line; -- ------------------------------ -- Test reading and writing on a socket stream. -- ------------------------------ procedure Test_Socket_Read (T : in out Test) is Stream : aliased Sockets.Socket_Stream; Writer : Util.Streams.Texts.Print_Stream; Server : Test_Server; Addr : GNAT.Sockets.Sock_Addr_Type; begin Server.Start; T.Assert (Server.Get_Port > 0, "The server was not started"); Addr := (GNAT.Sockets.Family_Inet, GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1), GNAT.Sockets.Port_Type (Server.Get_Port)); -- Let the server start. delay 0.1; -- Get a connection and write 10 lines. Stream.Connect (Server => Addr); Writer.Initialize (Output => Stream'Unchecked_Access, Size => 1024); for I in 1 .. 10 loop Writer.Write ("Sending a line on the socket test-" & Natural'Image (I) & ASCII.CR & ASCII.LF); Writer.Flush; end loop; Writer.Close; -- Stop the server and verify that 10 lines were received. Server.Stop; Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received"); end Test_Socket_Read; -- ------------------------------ -- Test socket initialization. -- ------------------------------ procedure Test_Socket_Init (T : in out Test) is Stream : aliased Sockets.Socket_Stream; Fd : GNAT.Sockets.Socket_Type; Addr : GNAT.Sockets.Sock_Addr_Type; begin Addr := (GNAT.Sockets.Family_Inet, GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1), 80); GNAT.Sockets.Create_Socket (Fd); Stream.Open (Fd); begin Stream.Connect (Addr); T.Assert (False, "No exception was raised"); exception when Ada.IO_Exceptions.Use_Error => null; end; end Test_Socket_Init; end Util.Streams.Sockets.Tests;
----------------------------------------------------------------------- -- util-streams-sockets-tests -- Unit tests for socket streams -- 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 Ada.Strings.Unbounded; with Ada.IO_Exceptions; with Util.Test_Caller; with Util.Streams.Texts; with Util.Tests.Servers; package body Util.Streams.Sockets.Tests is package Caller is new Util.Test_Caller (Test, "Streams.Sockets"); type Test_Server is new Util.Tests.Servers.Server with record Count : Natural := 0; end record; -- Process the line received by the server. overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect", Test_Socket_Init'Access); Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write", Test_Socket_Read'Access); end Add_Tests; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is pragma Unreferenced (Stream, Client); begin if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then Into.Count := Into.Count + 1; end if; end Process_Line; -- ------------------------------ -- Test reading and writing on a socket stream. -- ------------------------------ procedure Test_Socket_Read (T : in out Test) is Stream : aliased Sockets.Socket_Stream; Writer : Util.Streams.Texts.Print_Stream; Server : Test_Server; Addr : GNAT.Sockets.Sock_Addr_Type; begin Server.Start; T.Assert (Server.Get_Port > 0, "The server was not started"); Addr := (GNAT.Sockets.Family_Inet, GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1), GNAT.Sockets.Port_Type (Server.Get_Port)); -- Let the server start. delay 0.1; -- Get a connection and write 10 lines. Stream.Connect (Server => Addr); Writer.Initialize (Output => Stream'Unchecked_Access, Size => 1024); for I in 1 .. 10 loop Writer.Write ("Sending a line on the socket test-" & Natural'Image (I) & ASCII.CR & ASCII.LF); Writer.Flush; end loop; Writer.Close; -- Stop the server and verify that 10 lines were received. Server.Stop; Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received"); end Test_Socket_Read; -- ------------------------------ -- Test socket initialization. -- ------------------------------ procedure Test_Socket_Init (T : in out Test) is Stream : aliased Sockets.Socket_Stream; Fd : GNAT.Sockets.Socket_Type; Addr : GNAT.Sockets.Sock_Addr_Type; begin Addr := (GNAT.Sockets.Family_Inet, GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1), 80); GNAT.Sockets.Create_Socket (Fd); Stream.Open (Fd); begin Stream.Connect (Addr); T.Assert (False, "No exception was raised"); exception when Ada.IO_Exceptions.Use_Error => null; end; end Test_Socket_Init; end Util.Streams.Sockets.Tests;
Remove unused use Util.Tests clause
Remove unused use Util.Tests clause
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2aaea4d5728391ed926c7370669238f858d5b167
regtests/ado-schemas-tests.adb
regtests/ado-schemas-tests.adb
----------------------------------------------------------------------- -- ado-schemas-tests -- Test loading of database schema -- Copyright (C) 2009 - 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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"); Assert_Equals (T, "", Get_Default (C), "Column has a default value"); 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; Table := ADO.Schemas.Find_Table (Schema, "audit_property"); T.Assert (Table /= null, "Table schema for audit_property not found"); Assert_Equals (T, "audit_property", 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, 7, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "float_value"); begin T.Assert (C /= null, "Cannot find column 'float_value' in table schema"); Assert_Equals (T, "float_value", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_FLOAT, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (not Is_Binary (C), "Column is binary"); T.Assert (not Is_Primary (C), "Column must be not be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "double_value"); begin T.Assert (C /= null, "Cannot find column 'double_value' in table schema"); Assert_Equals (T, "double_value", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_DOUBLE, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (not Is_Binary (C), "Column is binary"); T.Assert (not Is_Primary (C), "Column must be not be a primary key"); 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, 11, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 11, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 11, 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 - 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.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"); Assert_Equals (T, "", Get_Default (C), "Column has a default value"); 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; Table := ADO.Schemas.Find_Table (Schema, "audit_property"); T.Assert (Table /= null, "Table schema for audit_property not found"); Assert_Equals (T, "audit_property", 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, 7, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "float_value"); begin T.Assert (C /= null, "Cannot find column 'float_value' in table schema"); Assert_Equals (T, "float_value", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_FLOAT, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (not Is_Binary (C), "Column is binary"); T.Assert (not Is_Primary (C), "Column must be not be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "double_value"); begin T.Assert (C /= null, "Cannot find column 'double_value' in table schema"); Assert_Equals (T, "double_value", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_DOUBLE, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (not Is_Binary (C), "Column is binary"); T.Assert (not Is_Primary (C), "Column must be not be a primary key"); 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, 12, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 12, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 12, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; -- ------------------------------ -- Test the creation of database. -- ------------------------------ procedure Test_Create_Schema (T : in out Test) is use ADO.Sessions.Sources; Msg : Util.Strings.Vectors.Vector; Cfg : Data_Source := Data_Source (Regtests.Get_Controller); Driver : constant String := Cfg.Get_Driver; Database : constant String := Cfg.Get_Database; Path : constant String := "db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql"; pragma Unreferenced (Msg); begin if Driver = "sqlite" then if Ada.Directories.Exists (Database & ".test") then Ada.Directories.Delete_File (Database & ".test"); end if; Cfg.Set_Database (Database & ".test"); ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); T.Assert (Ada.Directories.Exists (Database & ".test"), "The sqlite database was not created"); else ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); end if; end Test_Create_Schema; end ADO.Schemas.Tests;
Update the unit test to take into account the new table in the unit tests
Update the unit test to take into account the new table in the unit tests
Ada
apache-2.0
stcarrez/ada-ado
3e7ebfe0a633e978d9d8211920bb2168cc0cde29
src/asf-navigations-render.ads
src/asf-navigations-render.ads
----------------------------------------------------------------------- -- asf-navigations-render -- Navigator to render a page -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package ASF.Navigations.Render is -- ------------------------------ -- Render page navigator -- ------------------------------ -- The <b>Render_Navigator</b> defines the page that must be rendered for the response. type Render_Navigator is new Navigation_Case with private; type Render_Navigator_Access is access all Render_Navigator'Class; -- Navigate to the next page or action according to the controller's navigator. -- A navigator controller could redirect the user to another page, render a specific -- view or return some raw content. overriding procedure Navigate (Controller : in Render_Navigator; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Create a navigation case to render a view. function Create_Render_Navigator (To_View : in String) return Navigation_Access; private type Render_Navigator is new Navigation_Case with record View_Name : Unbounded_String; end record; end ASF.Navigations.Render;
----------------------------------------------------------------------- -- asf-navigations-render -- Navigator to render a page -- Copyright (C) 2010, 2011, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package ASF.Navigations.Render is -- ------------------------------ -- Render page navigator -- ------------------------------ -- The <b>Render_Navigator</b> defines the page that must be rendered for the response. type Render_Navigator (Len : Natural) is new Navigation_Case with private; type Render_Navigator_Access is access all Render_Navigator'Class; -- Navigate to the next page or action according to the controller's navigator. -- A navigator controller could redirect the user to another page, render a specific -- view or return some raw content. overriding procedure Navigate (Controller : in Render_Navigator; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Create a navigation case to render a view. function Create_Render_Navigator (To_View : in String; Status : in Natural) return Navigation_Access; private type Render_Navigator (Len : Natural) is new Navigation_Case with record Status : Natural := 0; View_Name : String (1 .. Len); end record; end ASF.Navigations.Render;
Update the Render_Navigator type to store the view name as a string and also store a status code Add a Status parameter to the Create_Render_Navigator function
Update the Render_Navigator type to store the view name as a string and also store a status code Add a Status parameter to the Create_Render_Navigator function
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
7dbb40411e7f7301a7ea72fa2e1e2db5d44065c2
mat/src/mat-readers-streams.adb
mat/src/mat-readers-streams.adb
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.IO_Exceptions; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Read a message from the stream. -- ------------------------------ overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message) is use type Ada.Streams.Stream_Element_Offset; Buffer : constant Util.Streams.Buffered.Buffer_Access := Msg.Buffer.Buffer; Last : Ada.Streams.Stream_Element_Offset; begin Reader.Stream.Read (Buffer (0 .. 1), Last); if Last /= 2 then raise Ada.IO_Exceptions.End_Error; end if; Msg.Buffer.Size := 2; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Buffer'Last then Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size)); raise Ada.IO_Exceptions.Data_Error; end if; Reader.Stream.Read (Buffer (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Buffer (Last)'Address; Msg.Buffer.Size := Msg.Size; Log.Debug ("Read message size {0}", Natural'Image (Msg.Size)); end Read_Message; -- ------------------------------ -- Read the events from the stream and stop when the end of the stream is reached. -- ------------------------------ procedure Read_All (Reader : in out Stream_Reader_Type) is use Ada.Streams; use type MAT.Types.Uint8; Buffer : aliased Buffer_Type; Msg : Message; Last : Ada.Streams.Stream_Element_Offset; Format : MAT.Types.Uint8; begin Reader.Data := new Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE); Msg.Buffer := Buffer'Unchecked_Access; Msg.Buffer.Start := Reader.Data (0)'Address; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Reader.Data (MAX_MSG_SIZE)'Address; Msg.Buffer.Size := 1; Buffer.Buffer := Reader.Data; Reader.Stream.Read (Reader.Data (0 .. 0), Last); Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); if Format = 0 then Msg.Buffer.Endian := LITTLE_ENDIAN; Log.Debug ("Data stream is little endian"); else Msg.Buffer.Endian := BIG_ENDIAN; Log.Debug ("Data stream is big endian"); end if; Reader.Read_Message (Msg); Reader.Read_Headers (Msg); while not Reader.Stream.Is_Eof loop Reader.Read_Message (Msg); Reader.Dispatch_Message (Msg); end loop; exception when Ada.IO_Exceptions.End_Error => null; end Read_All; end MAT.Readers.Streams;
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.IO_Exceptions; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Read a message from the stream. -- ------------------------------ overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message_Type) is use type Ada.Streams.Stream_Element_Offset; Buffer : constant Util.Streams.Buffered.Buffer_Access := Msg.Buffer.Buffer; Last : Ada.Streams.Stream_Element_Offset; begin Reader.Stream.Read (Buffer (0 .. 1), Last); if Last /= 2 then raise Ada.IO_Exceptions.End_Error; end if; Msg.Buffer.Size := 2; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Buffer'Last then Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size)); raise Ada.IO_Exceptions.Data_Error; end if; Reader.Stream.Read (Buffer (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Buffer (Last)'Address; Msg.Buffer.Size := Msg.Size; Log.Debug ("Read message size {0}", Natural'Image (Msg.Size)); end Read_Message; -- ------------------------------ -- Read the events from the stream and stop when the end of the stream is reached. -- ------------------------------ procedure Read_All (Reader : in out Stream_Reader_Type) is use Ada.Streams; use type MAT.Types.Uint8; Buffer : aliased Buffer_Type; Msg : Message; Last : Ada.Streams.Stream_Element_Offset; Format : MAT.Types.Uint8; begin Reader.Data := new Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE); Msg.Buffer := Buffer'Unchecked_Access; Msg.Buffer.Start := Reader.Data (0)'Address; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Reader.Data (MAX_MSG_SIZE)'Address; Msg.Buffer.Size := 1; Buffer.Buffer := Reader.Data; Reader.Stream.Read (Reader.Data (0 .. 0), Last); Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); if Format = 0 then Msg.Buffer.Endian := LITTLE_ENDIAN; Log.Debug ("Data stream is little endian"); else Msg.Buffer.Endian := BIG_ENDIAN; Log.Debug ("Data stream is big endian"); end if; Reader.Read_Message (Msg); Reader.Read_Event_Definitions (Msg); while not Reader.Stream.Is_Eof loop Reader.Read_Message (Msg); Reader.Dispatch_Message (Msg); end loop; exception when Ada.IO_Exceptions.End_Error => null; end Read_All; end MAT.Readers.Streams;
Call Read_Event_Definitions instead of Read_Headers
Call Read_Event_Definitions instead of Read_Headers
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
67893dd6b53046d590bb396854296c0da89702cd
src/security-oauth-clients.ads
src/security-oauth-clients.ads
----------------------------------------------------------------------- -- 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.Strings.Unbounded; with Security.Permissions; -- 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 Security.OAuth.Clients is -- ------------------------------ -- Access Token -- ------------------------------ -- Access tokens are credentials used to access protected resources. -- The access token is represented as a <b>Principal</b>. This is an opaque -- value for an application. type Access_Token (Len : Natural) is new Security.Principal with private; type Access_Token_Access is access all Access_Token'Class; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Access_Token) return String; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is tagged private; -- 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); -- 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); -- 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); -- 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); -- OAuth 2.0 Section 4.1.1 Authorization Request -- 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; -- 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; -- OAuth 2.0 Section 4.1.2 Authorization Response -- 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; -- OAuth 2.0 Section 4.1.3. Access Token Request -- Section 4.1.4. Access Token Response -- Exchange the OAuth code into an access token. function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access; -- Create the access token function Create_Access_Token (App : in Application; Token : in String; Expires : in Natural) return Access_Token_Access; private type Access_Token (Len : Natural) is new Security.Principal with record Access_Id : String (1 .. Len); end record; type Application is tagged record Client_Id : Ada.Strings.Unbounded.Unbounded_String; Secret : Ada.Strings.Unbounded.Unbounded_String; Callback : Ada.Strings.Unbounded.Unbounded_String; Request_URI : Ada.Strings.Unbounded.Unbounded_String; Protect : Ada.Strings.Unbounded.Unbounded_String; Key : Ada.Strings.Unbounded.Unbounded_String; end record; 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.Strings.Unbounded; -- 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 Security.OAuth.Clients is -- ------------------------------ -- Access Token -- ------------------------------ -- Access tokens are credentials used to access protected resources. -- The access token is represented as a <b>Principal</b>. This is an opaque -- value for an application. type Access_Token (Len : Natural) is new Security.Principal with private; type Access_Token_Access is access all Access_Token'Class; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Access_Token) return String; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is tagged private; -- 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); -- 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); -- 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); -- 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); -- OAuth 2.0 Section 4.1.1 Authorization Request -- 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; -- 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; -- OAuth 2.0 Section 4.1.2 Authorization Response -- 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; -- OAuth 2.0 Section 4.1.3. Access Token Request -- Section 4.1.4. Access Token Response -- Exchange the OAuth code into an access token. function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access; -- Create the access token function Create_Access_Token (App : in Application; Token : in String; Expires : in Natural) return Access_Token_Access; private type Access_Token (Len : Natural) is new Security.Principal with record Access_Id : String (1 .. Len); end record; type Application is tagged record Client_Id : Ada.Strings.Unbounded.Unbounded_String; Secret : Ada.Strings.Unbounded.Unbounded_String; Callback : Ada.Strings.Unbounded.Unbounded_String; Request_URI : Ada.Strings.Unbounded.Unbounded_String; Protect : Ada.Strings.Unbounded.Unbounded_String; Key : Ada.Strings.Unbounded.Unbounded_String; end record; end Security.OAuth.Clients;
Remove dependency to Security.Permissions
Remove dependency to Security.Permissions
Ada
apache-2.0
Letractively/ada-security
d8cae10cad24b916079ebee1306e53793280719a
regtests/util-strings-tests.ads
regtests/util-strings-tests.ads
----------------------------------------------------------------------- -- strings.tests -- Unit tests for Strings -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Strings.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Escape_Javascript (T : in out Test); procedure Test_Escape_Xml (T : in out Test); procedure Test_Unescape_Xml (T : in out Test); procedure Test_Capitalize (T : in out Test); procedure Test_To_Upper_Case (T : in out Test); procedure Test_To_Lower_Case (T : in out Test); procedure Test_To_Hex (T : in out Test); procedure Test_Measure_Copy (T : in out Test); procedure Test_Index (T : in out Test); procedure Test_Rindex (T : in out Test); procedure Test_Starts_With (T : in out Test); -- Do some benchmark on String -> X hash mapped. procedure Test_Measure_Hash (T : in out Test); -- Test String_Ref creation procedure Test_String_Ref (T : in out Test); -- Benchmark comparison between the use of Iterate vs Query_Element. procedure Test_Perf_Vector (T : in out Test); -- Test perfect hash (samples/gperfhash) procedure Test_Perfect_Hash (T : in out Test); -- Test the token iteration. procedure Test_Iterate_Token (T : in out Test); end Util.Strings.Tests;
----------------------------------------------------------------------- -- strings.tests -- Unit tests for Strings -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Strings.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Escape_Javascript (T : in out Test); procedure Test_Escape_Xml (T : in out Test); procedure Test_Unescape_Xml (T : in out Test); procedure Test_Capitalize (T : in out Test); procedure Test_To_Upper_Case (T : in out Test); procedure Test_To_Lower_Case (T : in out Test); procedure Test_To_Hex (T : in out Test); procedure Test_Measure_Copy (T : in out Test); procedure Test_Index (T : in out Test); procedure Test_Rindex (T : in out Test); procedure Test_Starts_With (T : in out Test); procedure Test_Ends_With (T : in out Test); -- Do some benchmark on String -> X hash mapped. procedure Test_Measure_Hash (T : in out Test); -- Test String_Ref creation procedure Test_String_Ref (T : in out Test); -- Benchmark comparison between the use of Iterate vs Query_Element. procedure Test_Perf_Vector (T : in out Test); -- Test perfect hash (samples/gperfhash) procedure Test_Perfect_Hash (T : in out Test); -- Test the token iteration. procedure Test_Iterate_Token (T : in out Test); end Util.Strings.Tests;
Declare the Test_Ends_With procedure
Declare the Test_Ends_With procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c4520cbb6f727412fc7b0514a264cc377ecf37aa
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with AWA.Tests.Helpers; with AWA.Tests.Helpers.Users; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Wikis.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space", Test_Create_Wiki_Space'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page", Test_Create_Wiki_Page'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content", Test_Create_Wiki_Content'Access); end Add_Tests; -- ------------------------------ -- Test creation of a wiki space. -- ------------------------------ procedure Test_Create_Wiki_Space (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; W2 : AWA.Wikis.Models.Wiki_Space_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Wikis.Modules.Get_Wiki_Module; T.Assert (T.Manager /= null, "There is no wiki manager"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); T.Assert (W.Is_Inserted, "The new wiki space was not created"); W.Set_Name ("Test wiki space update"); W.Set_Is_Public (True); T.Manager.Save_Wiki_Space (W); T.Manager.Load_Wiki_Space (Wiki => W2, Id => W.Get_Id); Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name), "Invalid wiki space name"); end Test_Create_Wiki_Space; -- ------------------------------ -- Test creation of a wiki page. -- ------------------------------ procedure Test_Create_Wiki_Page (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; P : AWA.Wikis.Models.Wiki_Page_Ref; C : AWA.Wikis.Models.Wiki_Content_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); P.Set_Name ("The page"); P.Set_Title ("The page title"); T.Manager.Create_Wiki_Page (W, P, C); T.Assert (P.Is_Inserted, "The new wiki page was not created"); end Test_Create_Wiki_Page; -- ------------------------------ -- Test creation of a wiki page content. -- ------------------------------ procedure Test_Create_Wiki_Content (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; P : AWA.Wikis.Models.Wiki_Page_Ref; C : AWA.Wikis.Models.Wiki_Content_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); P.Set_Name ("The page"); P.Set_Title ("The page title"); T.Manager.Create_Wiki_Page (W, P, C); C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN); C.Set_Content ("-- Title" & ASCII.LF & "A paragraph"); C.Set_Save_Comment ("A first version"); T.Manager.Create_Wiki_Content (P, C); T.Assert (C.Is_Inserted, "The new wiki content was not created"); T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author"); T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page"); end Test_Create_Wiki_Content; end AWA.Wikis.Modules.Tests;
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with ASF.Tests; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with AWA.Tests.Helpers; with AWA.Tests.Helpers.Users; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Wikis.Modules.Tests is use ASF.Tests; use Util.Tests; package Caller is new Util.Test_Caller (Test, "Wikis.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space", Test_Create_Wiki_Space'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page", Test_Create_Wiki_Page'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content", Test_Create_Wiki_Content'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Wiki_Page", Test_Wiki_Page'Access); end Add_Tests; -- ------------------------------ -- Test creation of a wiki space. -- ------------------------------ procedure Test_Create_Wiki_Space (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; W2 : AWA.Wikis.Models.Wiki_Space_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Wikis.Modules.Get_Wiki_Module; T.Assert (T.Manager /= null, "There is no wiki manager"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); T.Assert (W.Is_Inserted, "The new wiki space was not created"); W.Set_Name ("Test wiki space update"); W.Set_Is_Public (True); T.Manager.Save_Wiki_Space (W); T.Manager.Load_Wiki_Space (Wiki => W2, Id => W.Get_Id); Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name), "Invalid wiki space name"); end Test_Create_Wiki_Space; -- ------------------------------ -- Test creation of a wiki page. -- ------------------------------ procedure Test_Create_Wiki_Page (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; P : AWA.Wikis.Models.Wiki_Page_Ref; C : AWA.Wikis.Models.Wiki_Content_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); P.Set_Name ("Private"); P.Set_Title ("The page title"); T.Manager.Create_Wiki_Page (W, P, C); T.Assert (P.Is_Inserted, "The new wiki page was not created"); C := AWA.Wikis.Models.Null_Wiki_Content; P := AWA.Wikis.Models.Null_Wiki_Page; P.Set_Name ("Public"); P.Set_Title ("The page title (public)"); P.Set_Is_Public (True); T.Manager.Create_Wiki_Page (W, P, C); T.Assert (P.Is_Inserted, "The new wiki page was not created"); T.Assert (P.Get_Is_Public, "The new wiki page is not public"); end Test_Create_Wiki_Page; -- ------------------------------ -- Test creation of a wiki page content. -- ------------------------------ procedure Test_Create_Wiki_Content (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; P : AWA.Wikis.Models.Wiki_Page_Ref; C : AWA.Wikis.Models.Wiki_Content_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); T.Wiki_Id := W.Get_Id; P.Set_Name ("PrivatePage"); P.Set_Title ("The page title"); P.Set_Is_Public (False); T.Manager.Create_Wiki_Page (W, P, C); T.Private_Id := P.Get_Id; C := AWA.Wikis.Models.Null_Wiki_Content; C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN); C.Set_Content ("-- Title" & ASCII.LF & "A paragraph"); C.Set_Save_Comment ("A first version"); T.Manager.Create_Wiki_Content (P, C); T.Assert (C.Is_Inserted, "The new wiki content was not created"); T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author"); T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page"); P := AWA.Wikis.Models.Null_Wiki_Page; C := AWA.Wikis.Models.Null_Wiki_Content; P.Set_Name ("PublicPage"); P.Set_Title ("The public page title"); P.Set_Is_Public (True); T.Manager.Create_Wiki_Page (W, P, C); T.Public_Id := P.Get_Id; C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN); C.Set_Content ("-- Title" & ASCII.LF & "A paragraph" & ASCII.LF & "[Link](http://mylink.com)" & ASCII.LF & "[Image](my-image.png)"); C.Set_Save_Comment ("A first version"); T.Manager.Create_Wiki_Content (P, C); T.Assert (C.Is_Inserted, "The new wiki content was not created"); T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author"); T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page"); end Test_Create_Wiki_Content; procedure Test_Wiki_Page (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id)); Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id)); begin ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PublicPage", "wiki-public-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage)"); Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage page returned", Status => ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident, "wiki-public-info-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage info)"); Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned", Status => ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, "/wikis/history/" & Ident & "/" & Pub_Ident, "wiki-public-history-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage history)"); Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned", Status => ASF.Responses.SC_OK); Request.Remove_Attribute ("wikiView"); ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PrivatePage", "wiki-private-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PrivatePage)"); Assert_Matches (T, ".*Protected Wiki Page.*", Reply, "Invalid PrivatePage page returned", Status => ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent", "wiki-list-recent-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent)"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent/grid", "wiki-list-grid-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent/grid)"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular", "wiki-list-popular-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular)"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular/grid", "wiki-list-popular-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular/grid)"); end Test_Wiki_Page; end AWA.Wikis.Modules.Tests;
Implement Test_Wiki_Page to test the display of the wiki page (public mode), display of wiki history, wiki information and wiki list
Implement Test_Wiki_Page to test the display of the wiki page (public mode), display of wiki history, wiki information and wiki list
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
816abf27b2af7d654542ae4a243def2c3ea31813
awa/regtests/awa-mail-modules-tests.adb
awa/regtests/awa-mail-modules-tests.adb
----------------------------------------------------------------------- -- awa-mail-module-tests -- Unit tests for Mail module -- 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 Util.Test_Caller; with AWA.Events; package body AWA.Mail.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Mail.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message", Test_Create_Message'Access); Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message (CC:)", Test_Cc_Message'Access); Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message (BCC:)", Test_Bcc_Message'Access); end Add_Tests; -- ------------------------------ -- Create an email message with the given template and verify its content. -- ------------------------------ procedure Test_Mail_Message (T : in out Test; Name : in String) is use Util.Beans.Objects; Mail : constant AWA.Mail.Modules.Mail_Module_Access := AWA.Mail.Modules.Get_Mail_Module; Event : AWA.Events.Module_Event; Props : Util.Beans.Objects.Maps.Map; begin T.Assert (Mail /= null, "There is no current mail module"); Props.Insert ("name", To_Object (String '("joe"))); Props.Insert ("email", To_Object (String '("[email protected]"))); Mail.Send_Mail (Template => Name, Props => Props, Content => Event); end Test_Mail_Message; -- ------------------------------ -- Create an email message and verify its content. -- ------------------------------ procedure Test_Create_Message (T : in out Test) is begin T.Test_Mail_Message ("mail-info.html"); end Test_Create_Message; -- ------------------------------ -- Create an email message with Cc: and verify its content. -- ------------------------------ procedure Test_Cc_Message (T : in out Test) is begin T.Test_Mail_Message ("mail-cc.html"); end Test_Cc_Message; -- ------------------------------ -- Create an email message with Bcc: and verify its content. -- ------------------------------ procedure Test_Bcc_Message (T : in out Test) is begin T.Test_Mail_Message ("mail-bcc.html"); end Test_Bcc_Message; end AWA.Mail.Modules.Tests;
----------------------------------------------------------------------- -- awa-mail-module-tests -- Unit tests for Mail module -- Copyright (C) 2012, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with AWA.Events; package body AWA.Mail.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Mail.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message", Test_Create_Message'Access); Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message (CC:)", Test_Cc_Message'Access); Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message (BCC:)", Test_Bcc_Message'Access); end Add_Tests; -- ------------------------------ -- Create an email message with the given template and verify its content. -- ------------------------------ procedure Test_Mail_Message (T : in out Test; Name : in String) is use Util.Beans.Objects; Mail : constant AWA.Mail.Modules.Mail_Module_Access := AWA.Mail.Modules.Get_Mail_Module; Event : AWA.Events.Module_Event; Props : Util.Beans.Objects.Maps.Map; begin T.Assert (Mail /= null, "There is no current mail module"); Props.Insert ("name", To_Object (String '("joe"))); Props.Insert ("email", To_Object (String '("[email protected]"))); Mail.Send_Mail (Template => Name, Props => Props, Params => Props, Content => Event); end Test_Mail_Message; -- ------------------------------ -- Create an email message and verify its content. -- ------------------------------ procedure Test_Create_Message (T : in out Test) is begin T.Test_Mail_Message ("mail-info.html"); end Test_Create_Message; -- ------------------------------ -- Create an email message with Cc: and verify its content. -- ------------------------------ procedure Test_Cc_Message (T : in out Test) is begin T.Test_Mail_Message ("mail-cc.html"); end Test_Cc_Message; -- ------------------------------ -- Create an email message with Bcc: and verify its content. -- ------------------------------ procedure Test_Bcc_Message (T : in out Test) is begin T.Test_Mail_Message ("mail-bcc.html"); end Test_Bcc_Message; end AWA.Mail.Modules.Tests;
Update the mail unit test
Update the mail unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8394c019a158014ea7d09749006d2ba48c358c14
mat/src/matp.adb
mat/src/matp.adb
----------------------------------------------------------------------- -- mat-types -- Global types -- 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.IO_Exceptions; with Readline; with MAT.Commands; with MAT.Targets; procedure Matp is procedure Interactive_Loop is Target : MAT.Targets.Target_Type; begin loop declare Line : constant String := Readline.Get_Line ("matp>"); begin MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => return; end; end loop; exception when Ada.IO_Exceptions.End_Error => return; end Interactive_Loop; begin Interactive_Loop; end Matp;
----------------------------------------------------------------------- -- mat-types -- Global types -- 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.IO_Exceptions; with Readline; with MAT.Commands; with MAT.Targets; with Util.Log.Loggers; procedure Matp is procedure Interactive_Loop is Target : MAT.Targets.Target_Type; begin loop declare Line : constant String := Readline.Get_Line ("matp>"); begin MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => return; end; end loop; exception when Ada.IO_Exceptions.End_Error => return; end Interactive_Loop; begin Util.Log.Loggers.Initialize ("matp.properties"); Interactive_Loop; end Matp;
Use Util.Log.Loggers.Initialize to configure the loggers
Use Util.Log.Loggers.Initialize to configure the loggers
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e9f025e7ecd255769493f874fa750861abc24aa8
src/core/texts/util-texts-builders.adb
src/core/texts/util-texts-builders.adb
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Texts.Builders is -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Block (Size); else B.Next_Block := new Block (Source.Block_Size); end if; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Element_Type) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; procedure Inline_Append (Source : in out Builder) is B : Block_Access := Source.Current; Last : Natural; begin loop if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Process (B.Content (B.Last + 1 .. B.Len), Last); exit when Last > B.Len or Last <= B.Last; Source.Length := Source.Length + Last - B.Last; B.Last := Last; exit when Last < B.Len; end loop; end Inline_Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; procedure Inline_Iterate (Source : in Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Iterate; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Block := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream -- ------------------------------ procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List) is C : Element_Type; Old_Pos : Natural; N : Natural := 0; Pos : Natural := Message'First; First : Natural := Pos; begin -- Replace {N} with arg1, arg2, arg3 or ? while Pos <= Message'Last loop C := Message (Pos); if Element_Type'Pos (C) = Character'Pos ('{') and then Pos + 1 <= Message'Last then if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; N := 0; Pos := Pos + 1; C := Message (Pos); -- Handle {} replacement to emit the current argument and advance argument position. if Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Pos - 2; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; N := N + 1; else N := 0; Old_Pos := Pos - 1; loop if Element_Type'Pos (C) >= Character'Pos ('0') and Element_Type'Pos (C) <= Character'Pos ('9') then N := N * 10 + Natural (Element_Type'Pos (C) - Character'Pos ('0')); Pos := Pos + 1; if Pos > Message'Last then First := Old_Pos; exit; end if; elsif Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Old_Pos; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; exit; else First := Old_Pos; exit; end if; C := Message (Pos); end loop; end if; else Pos := Pos + 1; end if; end loop; if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; end Format; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; end Util.Texts.Builders;
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Texts.Builders is -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Block (Size); else B.Next_Block := new Block (Source.Block_Size); end if; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Element_Type) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; procedure Inline_Append (Source : in out Builder) is B : Block_Access := Source.Current; Last : Natural; begin loop if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Process (B.Content (B.Last + 1 .. B.Len), Last); exit when Last > B.Len or Last <= B.Last; Source.Length := Source.Length + Last - B.Last; B.Last := Last; exit when Last < B.Len; end loop; end Inline_Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; procedure Inline_Iterate (Source : in Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Iterate; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Block := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Get the element at the given position. -- ------------------------------ function Element (Source : in Builder; Position : in Positive) return Element_Type is begin if Position <= Source.First.Last then return Source.First.Content (Position); else declare Pos : Positive := Position - Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if Pos <= B.Last then return B.Content (Pos); end if; Pos := Pos - B.Last; B := B.Next_Block; end loop; end; end if; end Element; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream -- ------------------------------ procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List) is C : Element_Type; Old_Pos : Natural; N : Natural := 0; Pos : Natural := Message'First; First : Natural := Pos; begin -- Replace {N} with arg1, arg2, arg3 or ? while Pos <= Message'Last loop C := Message (Pos); if Element_Type'Pos (C) = Character'Pos ('{') and then Pos + 1 <= Message'Last then if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; N := 0; Pos := Pos + 1; C := Message (Pos); -- Handle {} replacement to emit the current argument and advance argument position. if Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Pos - 2; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; N := N + 1; else N := 0; Old_Pos := Pos - 1; loop if Element_Type'Pos (C) >= Character'Pos ('0') and Element_Type'Pos (C) <= Character'Pos ('9') then N := N * 10 + Natural (Element_Type'Pos (C) - Character'Pos ('0')); Pos := Pos + 1; if Pos > Message'Last then First := Old_Pos; exit; end if; elsif Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Old_Pos; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; exit; else First := Old_Pos; exit; end if; C := Message (Pos); end loop; end if; else Pos := Pos + 1; end if; end loop; if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; end Format; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; end Util.Texts.Builders;
Implement the Element function
Implement the Element function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
702829c614216b5c737052d54969314636ed7126
matp/src/events/mat-events-tools.ads
matp/src/events/mat-events-tools.ads
----------------------------------------------------------------------- -- mat-events-tools - Profiler Events Description -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; package MAT.Events.Tools is Not_Found : exception; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event_Type); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Target_Event_Type; type Event_Info_Type is record First_Event : Target_Event_Type; Last_Event : Target_Event_Type; Frame_Addr : MAT.Types.Target_Addr; Count : Natural; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 0; Alloc_Size : MAT.Types.Target_Size := 0; Free_Size : MAT.Types.Target_Size := 0; end record; -- Collect statistics information about events. procedure Collect_Info (Into : in out Event_Info_Type; Event : in MAT.Events.Target_Event_Type); package Size_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Event_Info_Type); subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map; subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor; -- The frame key is composed of the frame address and the frame level. type Frame_Key_Type is record Addr : MAT.Types.Target_Addr; Level : Natural; end record; function "<" (Left, Right : in Frame_Key_Type) return Boolean; -- Ordered map to collect event info statistics by <frame, level> pair. package Frame_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Frame_Key_Type, Element_Type => Event_Info_Type); subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map; subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor; package Event_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Event_Info_Type); subtype Event_Info_Vector is Event_Info_Vectors.Vector; subtype Event_Info_Cursor is Event_Info_Vectors.Cursor; -- Extract from the frame info map, the list of event info sorted on the count. procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector); type Frame_Info_Type is record Key : Frame_Key_Type; Info : Event_Info_Type; end record; package Frame_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Frame_Info_Type); subtype Frame_Info_Vector is Frame_Info_Vectors.Vector; subtype Frame_Info_Cursor is Frame_Info_Vectors.Cursor; -- Extract from the frame info map, the list of frame event info sorted -- on the frame level and slot size. procedure Build_Frame_Info (Map : in Frame_Event_Info_Map; List : in out Frame_Info_Vector); end MAT.Events.Tools;
----------------------------------------------------------------------- -- mat-events-tools - Profiler Events Description -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; package MAT.Events.Tools is Not_Found : exception; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event_Type); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Target_Event_Type; type Event_Info_Type is record First_Event : Target_Event_Type; Last_Event : Target_Event_Type; Count : Natural := 0; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 0; Alloc_Size : MAT.Types.Target_Size := 0; Free_Size : MAT.Types.Target_Size := 0; end record; -- Collect statistics information about events. procedure Collect_Info (Into : in out Event_Info_Type; Event : in MAT.Events.Target_Event_Type); package Size_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Event_Info_Type); subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map; subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor; -- The frame key is composed of the frame address and the frame level. type Frame_Key_Type is record Addr : MAT.Types.Target_Addr; Level : Natural; end record; function "<" (Left, Right : in Frame_Key_Type) return Boolean; -- Ordered map to collect event info statistics by <frame, level> pair. package Frame_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Frame_Key_Type, Element_Type => Event_Info_Type); subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map; subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor; package Event_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Event_Info_Type); subtype Event_Info_Vector is Event_Info_Vectors.Vector; subtype Event_Info_Cursor is Event_Info_Vectors.Cursor; -- Extract from the frame info map, the list of event info sorted on the count. procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector); type Frame_Info_Type is record Key : Frame_Key_Type; Info : Event_Info_Type; end record; package Frame_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Frame_Info_Type); subtype Frame_Info_Vector is Frame_Info_Vectors.Vector; subtype Frame_Info_Cursor is Frame_Info_Vectors.Cursor; -- Extract from the frame info map, the list of frame event info sorted -- on the frame level and slot size. procedure Build_Frame_Info (Map : in Frame_Event_Info_Map; List : in out Frame_Info_Vector); end MAT.Events.Tools;
Remove the Frame_Addr from the Event_Info_Type and setup the Count to 0
Remove the Frame_Addr from the Event_Info_Type and setup the Count to 0
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
61660f2cfbc08a507e87a5b345d66c152af2e8b9
samples/xmi.adb
samples/xmi.adb
----------------------------------------------------------------------- -- xmi -- XMI parser example -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Util.Log.Loggers; with Util.Beans; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; -- This sample reads an UML 1.4 model saved in XMI 1.2 format. It uses the serialization -- framework to indicate what XML nodes and attributes must be reported. procedure XMI is use type Ada.Text_IO.Count; Reader : Util.Serialize.IO.XML.Parser; Count : constant Natural := Ada.Command_Line.Argument_Count; type XMI_Fields is (FIELD_CLASS_NAME, FIELD_CLASS_ID, FIELD_STEREOTYPE, FIELD_ATTRIBUTE_NAME, FIELD_PACKAGE_NAME, FIELD_PACKAGE_END, FIELD_VISIBILITY, FIELD_DATA_TYPE, FIELD_ENUM_DATA_TYPE, FIELD_ENUM_NAME, FIELD_ENUM_END, FIELD_ENUM_LITERAL, FIELD_ENUM_LITERAL_END, FIELD_CLASS_END, FIELD_MULTIPLICITY_LOWER, FIELD_MULTIPLICITY_UPPER, FIELD_ASSOCIATION_AGGREGATION, FIELD_ASSOCIATION_NAME, FIELD_ASSOCIATION_VISIBILITY, FIELD_ASSOCIATION_END_ID, FIELD_ASSOCIATION_END, FIELD_TAG_DEFINITION_ID, FIELD_TAG_DEFINITION_NAME, FIELD_OPERATION_NAME, FIELD_COMMENT_NAME, FIELD_COMMENT_BODY, FIELD_COMMENT_CLASS_ID, FIELD_TAGGED_VALUE_TYPE, FIELD_TAGGED_VALUE_VALUE); type XMI_Info is record Indent : Ada.Text_IO.Count := 1; end record; type XMI_Access is access all XMI_Info; procedure Set_Member (P : in out XMI_Info; Field : in XMI_Fields; Value : in Util.Beans.Objects.Object); procedure Print (Col : in Ada.Text_IO.Count; Line : in String) is begin Ada.Text_IO.Set_Col (Col); Ada.Text_IO.Put_Line (Line); end Print; procedure Set_Member (P : in out XMI_Info; Field : in XMI_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CLASS_NAME => Print (P.Indent, "Class " & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_VISIBILITY => Print (P.Indent, "visibility: " & Util.Beans.Objects.To_String (Value)); when FIELD_CLASS_ID => Print (P.Indent, "id: " & Util.Beans.Objects.To_String (Value)); when FIELD_ATTRIBUTE_NAME => Ada.Text_IO.Set_Col (P.Indent); Ada.Text_IO.Put ("attr: " & Util.Beans.Objects.To_String (Value)); when FIELD_MULTIPLICITY_LOWER => Ada.Text_IO.Set_Col (P.Indent); Ada.Text_IO.Put (" multiplicity: " & Util.Beans.Objects.To_String (Value)); when FIELD_MULTIPLICITY_UPPER => Ada.Text_IO.Put_Line (".." & Util.Beans.Objects.To_String (Value)); when FIELD_STEREOTYPE => Print (P.Indent, "<<" & Util.Beans.Objects.To_String (Value) & ">>"); when FIELD_DATA_TYPE => Print (P.Indent, " data-type:" & Util.Beans.Objects.To_String (Value)); when FIELD_ENUM_DATA_TYPE => Print (P.Indent, " enum-type:" & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_ENUM_NAME => Print (P.Indent, " enum " & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_ENUM_LITERAL => Print (P.Indent, " enum:" & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_OPERATION_NAME => Print (P.Indent, "operation:" & Util.Beans.Objects.To_String (Value)); when FIELD_ASSOCIATION_NAME => Print (P.Indent, "association " & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_ASSOCIATION_VISIBILITY => Print (P.Indent, "visibility: " & Util.Beans.Objects.To_String (Value)); when FIELD_ASSOCIATION_AGGREGATION => Print (P.Indent, " aggregate: " & Util.Beans.Objects.To_String (Value)); when FIELD_ASSOCIATION_END_ID => Print (P.Indent, " end-id: " & Util.Beans.Objects.To_String (Value)); when FIELD_PACKAGE_NAME => Print (P.Indent, "package " & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_TAGGED_VALUE_VALUE => Print (P.Indent, "-- " & Util.Beans.Objects.To_String (Value)); when FIELD_TAGGED_VALUE_TYPE => Print (P.Indent, "tag-type: " & Util.Beans.Objects.To_String (Value)); when FIELD_TAG_DEFINITION_NAME => Print (P.Indent, "Tag: " & Util.Beans.Objects.To_String (Value)); when FIELD_TAG_DEFINITION_ID => Print (P.Indent, " tag-id: " & Util.Beans.Objects.To_String (Value)); when FIELD_COMMENT_NAME => Print (P.Indent, "Comment: " & Util.Beans.Objects.To_String (Value)); when FIELD_COMMENT_BODY => Print (P.Indent, " text: " & Util.Beans.Objects.To_String (Value)); when FIELD_COMMENT_CLASS_ID => Print (P.Indent, " for-id: " & Util.Beans.Objects.To_String (Value)); when FIELD_PACKAGE_END | FIELD_CLASS_END | FIELD_ENUM_END | FIELD_ENUM_LITERAL_END | FIELD_ASSOCIATION_END => P.Indent := P.Indent - 2; end case; end Set_Member; package XMI_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => XMI_Info, Element_Type_Access => XMI_Access, Fields => XMI_Fields, Set_Member => Set_Member); XMI_Mapping : aliased XMI_Mapper.Mapper; Mapper : Util.Serialize.Mappers.Processing; begin -- Util.Log.Loggers.Initialize ("samples/log4j.properties"); if Count = 0 then Ada.Text_IO.Put_Line ("Usage: xmi file..."); Ada.Text_IO.Put_Line ("Example xmi samples/demo-atlas.xmi"); return; end if; -- Define the XMI mapping. XMI_Mapping.Add_Mapping ("**/Package/@name", FIELD_PACKAGE_NAME); XMI_Mapping.Add_Mapping ("**/Package/@visibility", FIELD_VISIBILITY); XMI_Mapping.Add_Mapping ("**/Package", FIELD_PACKAGE_END); XMI_Mapping.Add_Mapping ("**/Class/@name", FIELD_CLASS_NAME); XMI_Mapping.Add_Mapping ("**/Class/@xmi.idref", FIELD_CLASS_NAME); XMI_Mapping.Add_Mapping ("**/Class/@xmi.id", FIELD_CLASS_ID); XMI_Mapping.Add_Mapping ("**/Class/@visibility", FIELD_VISIBILITY); XMI_Mapping.Add_Mapping ("**/Class", FIELD_CLASS_END); XMI_Mapping.Add_Mapping ("**/Stereotype/@href", FIELD_STEREOTYPE); XMI_Mapping.Add_Mapping ("**/Stereotype/@name", FIELD_STEREOTYPE); XMI_Mapping.Add_Mapping ("**/Attribute/@name", FIELD_ATTRIBUTE_NAME); XMI_Mapping.Add_Mapping ("**/Attribute/@visibility", FIELD_VISIBILITY); XMI_Mapping.Add_Mapping ("**/TaggedValue.dataValue", FIELD_TAGGED_VALUE_VALUE); XMI_Mapping.Add_Mapping ("**/DataType/@href", FIELD_DATA_TYPE); XMI_Mapping.Add_Mapping ("**/Enumeration/@href", FIELD_ENUM_NAME); XMI_Mapping.Add_Mapping ("**/Enumeration/@name", FIELD_ENUM_NAME); XMI_Mapping.Add_Mapping ("**/Enumeration", FIELD_ENUM_END); XMI_Mapping.Add_Mapping ("**/EnumerationLiteral/@name", FIELD_ENUM_LITERAL); XMI_Mapping.Add_Mapping ("**/EnumerationLiteral", FIELD_ENUM_LITERAL_END); XMI_Mapping.Add_Mapping ("**/MultiplicityRange/@lower", FIELD_MULTIPLICITY_LOWER); XMI_Mapping.Add_Mapping ("**/MultiplicityRange/@upper", FIELD_MULTIPLICITY_UPPER); XMI_Mapping.Add_Mapping ("**/Operation/@name", FIELD_OPERATION_NAME); XMI_Mapping.Add_Mapping ("**/Operation/@visibility", FIELD_VISIBILITY); XMI_Mapping.Add_Mapping ("**/Association/@name", FIELD_ASSOCIATION_NAME); XMI_Mapping.Add_Mapping ("**/Association/@visibility", FIELD_ASSOCIATION_VISIBILITY); XMI_Mapping.Add_Mapping ("**/Association/@aggregation", FIELD_ASSOCIATION_AGGREGATION); XMI_Mapping.Add_Mapping ("**/AssociationEnd.participant/Class/@xmi.idref", FIELD_ASSOCIATION_END_ID); XMI_Mapping.Add_Mapping ("**/Association", FIELD_ASSOCIATION_END); XMI_Mapping.Add_Mapping ("**/TagDefinition/@name", FIELD_TAG_DEFINITION_NAME); XMI_Mapping.Add_Mapping ("**/TagDefinition/@xm.id", FIELD_TAG_DEFINITION_ID); XMI_Mapping.Add_Mapping ("**/Comment/@name", FIELD_COMMENT_NAME); XMI_Mapping.Add_Mapping ("**/Comment/@body", FIELD_COMMENT_BODY); XMI_Mapping.Add_Mapping ("**/Comment/Comment.annotatedElement/Class/@xmi.idref", FIELD_COMMENT_CLASS_ID); Mapper.Add_Mapping ("XMI", XMI_Mapping'Unchecked_Access); for I in 1 .. Count loop declare S : constant String := Ada.Command_Line.Argument (I); Data : aliased XMI_Info; begin XMI_Mapper.Set_Context (Mapper, Data'Unchecked_Access); Reader.Parse (S, Mapper); end; end loop; end XMI;
----------------------------------------------------------------------- -- xmi -- XMI parser example -- Copyright (C) 2012, 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.Text_IO; with Ada.Command_Line; with Util.Beans; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; -- This sample reads an UML 1.4 model saved in XMI 1.2 format. It uses the serialization -- framework to indicate what XML nodes and attributes must be reported. procedure XMI is use type Ada.Text_IO.Count; Reader : Util.Serialize.IO.XML.Parser; Count : constant Natural := Ada.Command_Line.Argument_Count; type XMI_Fields is (FIELD_CLASS_NAME, FIELD_CLASS_ID, FIELD_STEREOTYPE, FIELD_ATTRIBUTE_NAME, FIELD_PACKAGE_NAME, FIELD_PACKAGE_END, FIELD_VISIBILITY, FIELD_DATA_TYPE, FIELD_ENUM_DATA_TYPE, FIELD_ENUM_NAME, FIELD_ENUM_END, FIELD_ENUM_LITERAL, FIELD_ENUM_LITERAL_END, FIELD_CLASS_END, FIELD_MULTIPLICITY_LOWER, FIELD_MULTIPLICITY_UPPER, FIELD_ASSOCIATION_AGGREGATION, FIELD_ASSOCIATION_NAME, FIELD_ASSOCIATION_VISIBILITY, FIELD_ASSOCIATION_END_ID, FIELD_ASSOCIATION_END, FIELD_TAG_DEFINITION_ID, FIELD_TAG_DEFINITION_NAME, FIELD_OPERATION_NAME, FIELD_COMMENT_NAME, FIELD_COMMENT_BODY, FIELD_COMMENT_CLASS_ID, FIELD_TAGGED_VALUE_TYPE, FIELD_TAGGED_VALUE_VALUE); type XMI_Info is record Indent : Ada.Text_IO.Count := 1; end record; type XMI_Access is access all XMI_Info; procedure Set_Member (P : in out XMI_Info; Field : in XMI_Fields; Value : in Util.Beans.Objects.Object); procedure Print (Col : in Ada.Text_IO.Count; Line : in String); procedure Print (Col : in Ada.Text_IO.Count; Line : in String) is begin Ada.Text_IO.Set_Col (Col); Ada.Text_IO.Put_Line (Line); end Print; procedure Set_Member (P : in out XMI_Info; Field : in XMI_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CLASS_NAME => Print (P.Indent, "Class " & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_VISIBILITY => Print (P.Indent, "visibility: " & Util.Beans.Objects.To_String (Value)); when FIELD_CLASS_ID => Print (P.Indent, "id: " & Util.Beans.Objects.To_String (Value)); when FIELD_ATTRIBUTE_NAME => Ada.Text_IO.Set_Col (P.Indent); Ada.Text_IO.Put ("attr: " & Util.Beans.Objects.To_String (Value)); when FIELD_MULTIPLICITY_LOWER => Ada.Text_IO.Set_Col (P.Indent); Ada.Text_IO.Put (" multiplicity: " & Util.Beans.Objects.To_String (Value)); when FIELD_MULTIPLICITY_UPPER => Ada.Text_IO.Put_Line (".." & Util.Beans.Objects.To_String (Value)); when FIELD_STEREOTYPE => Print (P.Indent, "<<" & Util.Beans.Objects.To_String (Value) & ">>"); when FIELD_DATA_TYPE => Print (P.Indent, " data-type:" & Util.Beans.Objects.To_String (Value)); when FIELD_ENUM_DATA_TYPE => Print (P.Indent, " enum-type:" & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_ENUM_NAME => Print (P.Indent, " enum " & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_ENUM_LITERAL => Print (P.Indent, " enum:" & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_OPERATION_NAME => Print (P.Indent, "operation:" & Util.Beans.Objects.To_String (Value)); when FIELD_ASSOCIATION_NAME => Print (P.Indent, "association " & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_ASSOCIATION_VISIBILITY => Print (P.Indent, "visibility: " & Util.Beans.Objects.To_String (Value)); when FIELD_ASSOCIATION_AGGREGATION => Print (P.Indent, " aggregate: " & Util.Beans.Objects.To_String (Value)); when FIELD_ASSOCIATION_END_ID => Print (P.Indent, " end-id: " & Util.Beans.Objects.To_String (Value)); when FIELD_PACKAGE_NAME => Print (P.Indent, "package " & Util.Beans.Objects.To_String (Value)); P.Indent := P.Indent + 2; when FIELD_TAGGED_VALUE_VALUE => Print (P.Indent, "-- " & Util.Beans.Objects.To_String (Value)); when FIELD_TAGGED_VALUE_TYPE => Print (P.Indent, "tag-type: " & Util.Beans.Objects.To_String (Value)); when FIELD_TAG_DEFINITION_NAME => Print (P.Indent, "Tag: " & Util.Beans.Objects.To_String (Value)); when FIELD_TAG_DEFINITION_ID => Print (P.Indent, " tag-id: " & Util.Beans.Objects.To_String (Value)); when FIELD_COMMENT_NAME => Print (P.Indent, "Comment: " & Util.Beans.Objects.To_String (Value)); when FIELD_COMMENT_BODY => Print (P.Indent, " text: " & Util.Beans.Objects.To_String (Value)); when FIELD_COMMENT_CLASS_ID => Print (P.Indent, " for-id: " & Util.Beans.Objects.To_String (Value)); when FIELD_PACKAGE_END | FIELD_CLASS_END | FIELD_ENUM_END | FIELD_ENUM_LITERAL_END | FIELD_ASSOCIATION_END => P.Indent := P.Indent - 2; end case; end Set_Member; package XMI_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => XMI_Info, Element_Type_Access => XMI_Access, Fields => XMI_Fields, Set_Member => Set_Member); XMI_Mapping : aliased XMI_Mapper.Mapper; Mapper : Util.Serialize.Mappers.Processing; begin -- Util.Log.Loggers.Initialize ("samples/log4j.properties"); if Count = 0 then Ada.Text_IO.Put_Line ("Usage: xmi file..."); Ada.Text_IO.Put_Line ("Example xmi samples/demo-atlas.xmi"); return; end if; -- Define the XMI mapping. XMI_Mapping.Add_Mapping ("**/Package/@name", FIELD_PACKAGE_NAME); XMI_Mapping.Add_Mapping ("**/Package/@visibility", FIELD_VISIBILITY); XMI_Mapping.Add_Mapping ("**/Package", FIELD_PACKAGE_END); XMI_Mapping.Add_Mapping ("**/Class/@name", FIELD_CLASS_NAME); XMI_Mapping.Add_Mapping ("**/Class/@xmi.idref", FIELD_CLASS_NAME); XMI_Mapping.Add_Mapping ("**/Class/@xmi.id", FIELD_CLASS_ID); XMI_Mapping.Add_Mapping ("**/Class/@visibility", FIELD_VISIBILITY); XMI_Mapping.Add_Mapping ("**/Class", FIELD_CLASS_END); XMI_Mapping.Add_Mapping ("**/Stereotype/@href", FIELD_STEREOTYPE); XMI_Mapping.Add_Mapping ("**/Stereotype/@name", FIELD_STEREOTYPE); XMI_Mapping.Add_Mapping ("**/Attribute/@name", FIELD_ATTRIBUTE_NAME); XMI_Mapping.Add_Mapping ("**/Attribute/@visibility", FIELD_VISIBILITY); XMI_Mapping.Add_Mapping ("**/TaggedValue.dataValue", FIELD_TAGGED_VALUE_VALUE); XMI_Mapping.Add_Mapping ("**/DataType/@href", FIELD_DATA_TYPE); XMI_Mapping.Add_Mapping ("**/Enumeration/@href", FIELD_ENUM_NAME); XMI_Mapping.Add_Mapping ("**/Enumeration/@name", FIELD_ENUM_NAME); XMI_Mapping.Add_Mapping ("**/Enumeration", FIELD_ENUM_END); XMI_Mapping.Add_Mapping ("**/EnumerationLiteral/@name", FIELD_ENUM_LITERAL); XMI_Mapping.Add_Mapping ("**/EnumerationLiteral", FIELD_ENUM_LITERAL_END); XMI_Mapping.Add_Mapping ("**/MultiplicityRange/@lower", FIELD_MULTIPLICITY_LOWER); XMI_Mapping.Add_Mapping ("**/MultiplicityRange/@upper", FIELD_MULTIPLICITY_UPPER); XMI_Mapping.Add_Mapping ("**/Operation/@name", FIELD_OPERATION_NAME); XMI_Mapping.Add_Mapping ("**/Operation/@visibility", FIELD_VISIBILITY); XMI_Mapping.Add_Mapping ("**/Association/@name", FIELD_ASSOCIATION_NAME); XMI_Mapping.Add_Mapping ("**/Association/@visibility", FIELD_ASSOCIATION_VISIBILITY); XMI_Mapping.Add_Mapping ("**/Association/@aggregation", FIELD_ASSOCIATION_AGGREGATION); XMI_Mapping.Add_Mapping ("**/AssociationEnd.participant/Class/@xmi.idref", FIELD_ASSOCIATION_END_ID); XMI_Mapping.Add_Mapping ("**/Association", FIELD_ASSOCIATION_END); XMI_Mapping.Add_Mapping ("**/TagDefinition/@name", FIELD_TAG_DEFINITION_NAME); XMI_Mapping.Add_Mapping ("**/TagDefinition/@xm.id", FIELD_TAG_DEFINITION_ID); XMI_Mapping.Add_Mapping ("**/Comment/@name", FIELD_COMMENT_NAME); XMI_Mapping.Add_Mapping ("**/Comment/@body", FIELD_COMMENT_BODY); XMI_Mapping.Add_Mapping ("**/Comment/Comment.annotatedElement/Class/@xmi.idref", FIELD_COMMENT_CLASS_ID); Mapper.Add_Mapping ("XMI", XMI_Mapping'Unchecked_Access); for I in 1 .. Count loop declare S : constant String := Ada.Command_Line.Argument (I); Data : aliased XMI_Info; begin XMI_Mapper.Set_Context (Mapper, Data'Unchecked_Access); Reader.Parse (S, Mapper); end; end loop; end XMI;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8977e13bfe2c1c5df4a2ff65795af69748e9d18a
samples/date.adb
samples/date.adb
----------------------------------------------------------------------- -- date -- Print the date -- Copyright (C) 2011, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Ada.Strings.Unbounded; with GNAT.Command_Line; with Util.Log.Loggers; with Util.Dates.Formats; with Util.Properties.Bundles; procedure Date is use type Ada.Calendar.Time; use Util.Log.Loggers; use Ada.Strings.Unbounded; use Util.Properties.Bundles; use GNAT.Command_Line; Log : constant Logger := Create ("log"); Factory : Util.Properties.Bundles.Loader; Bundle : Util.Properties.Bundles.Manager; Locale : Unbounded_String := To_Unbounded_String ("en"); Date : constant Ada.Calendar.Time := Ada.Calendar.Clock; Use_Default : Boolean := True; begin Util.Log.Loggers.Initialize ("samples/log4j.properties"); -- Load the bundles from the current directory Initialize (Factory, "samples/;bundles"); loop case Getopt ("h l: locale: help") is when ASCII.NUL => exit; when 'l' => Locale := To_Unbounded_String (Parameter); when others => raise GNAT.Command_Line.Invalid_Switch; end case; end loop; begin Load_Bundle (Factory, "dates", To_String (Locale), Bundle); exception when NO_BUNDLE => Log.Error ("There is no bundle: {0}", "dates"); end; loop declare Pattern : constant String := Get_Argument; begin exit when Pattern = ""; Use_Default := False; Ada.Text_IO.Put_Line (Util.Dates.Formats.Format (Pattern => Pattern, Date => Date, Bundle => Bundle)); end; end loop; if Use_Default then Ada.Text_IO.Put_Line (Util.Dates.Formats.Format (Pattern => "%a %b %_d %T %Y", Date => Date, Bundle => Bundle)); end if; exception when GNAT.Command_Line.Invalid_Switch => Log.Error ("Usage: date -l locale format"); end Date;
----------------------------------------------------------------------- -- date -- Print the date -- Copyright (C) 2011, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Ada.Strings.Unbounded; with GNAT.Command_Line; with Util.Log.Loggers; with Util.Dates.Formats; with Util.Properties.Bundles; procedure Date is use Util.Log.Loggers; use Ada.Strings.Unbounded; use Util.Properties.Bundles; use GNAT.Command_Line; Log : constant Logger := Create ("log"); Factory : Util.Properties.Bundles.Loader; Bundle : Util.Properties.Bundles.Manager; Locale : Unbounded_String := To_Unbounded_String ("en"); Date : constant Ada.Calendar.Time := Ada.Calendar.Clock; Use_Default : Boolean := True; begin Util.Log.Loggers.Initialize ("samples/log4j.properties"); -- Load the bundles from the current directory Initialize (Factory, "samples/;bundles"); loop case Getopt ("h l: locale: help") is when ASCII.NUL => exit; when 'l' => Locale := To_Unbounded_String (Parameter); when others => raise GNAT.Command_Line.Invalid_Switch; end case; end loop; begin Load_Bundle (Factory, "dates", To_String (Locale), Bundle); exception when NO_BUNDLE => Log.Error ("There is no bundle: {0}", "dates"); end; loop declare Pattern : constant String := Get_Argument; begin exit when Pattern = ""; Use_Default := False; Ada.Text_IO.Put_Line (Util.Dates.Formats.Format (Pattern => Pattern, Date => Date, Bundle => Bundle)); end; end loop; if Use_Default then Ada.Text_IO.Put_Line (Util.Dates.Formats.Format (Pattern => "%a %b %_d %T %Y", Date => Date, Bundle => Bundle)); end if; exception when GNAT.Command_Line.Invalid_Switch => Log.Error ("Usage: date -l locale format"); end Date;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f3e2c87312486eeb35143c499274000625e575f0
regtests/ado-schemas-tests.adb
regtests/ado-schemas-tests.adb
----------------------------------------------------------------------- -- ado-schemas-tests -- Test loading of database schema -- Copyright (C) 2009 - 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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, 11, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 11, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 11, 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 - 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.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"); Assert_Equals (T, "", Get_Default (C), "Column has a default value"); 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; Table := ADO.Schemas.Find_Table (Schema, "audit_property"); T.Assert (Table /= null, "Table schema for audit_property not found"); Assert_Equals (T, "audit_property", 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, 7, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "float_value"); begin T.Assert (C /= null, "Cannot find column 'float_value' in table schema"); Assert_Equals (T, "float_value", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_FLOAT, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (not Is_Binary (C), "Column is binary"); T.Assert (not Is_Primary (C), "Column must be not be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "double_value"); begin T.Assert (C /= null, "Cannot find column 'double_value' in table schema"); Assert_Equals (T, "double_value", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_DOUBLE, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (not Is_Binary (C), "Column is binary"); T.Assert (not Is_Primary (C), "Column must be not be a primary key"); 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, 11, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 11, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 11, 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 more schema checks with float columns
Add more schema checks with float columns
Ada
apache-2.0
stcarrez/ada-ado
877878c63d9a581f8e7109e3c33f6ddae529ec9f
awa/awaunit/awa-tests-helpers-users.adb
awa/awaunit/awa-tests-helpers-users.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join awa_email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- Simulate a user login in the given service context. procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); end Login; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- 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.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join awa_email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- ------------------------------ -- Simulate a user login in the given service context. -- ------------------------------ procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); end Login; -- ------------------------------ -- Setup the context and security context to simulate an anonymous user. -- ------------------------------ procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Context.Set_Context (App, null); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => null); end Anonymous; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
Implement the Anonymous procedure to simulate anonymous users
Implement the Anonymous procedure to simulate anonymous users
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
29f6a0afe1d4e07e0e7904e201156a55c554ba7c
regtests/security-permissions-tests.adb
regtests/security-permissions-tests.adb
----------------------------------------------------------------------- -- Security-permissions-tests - Unit tests for Security.Permissions -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; package body Security.Permissions.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Permissions"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Add_Permission", Test_Add_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index", Test_Add_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Add_Permission and Get_Permission_Index -- ------------------------------ procedure Test_Add_Permission (T : in out Test) is Index1, Index2 : Permission_Index; begin Add_Permission ("test-create-permission", Index1); T.Assert (Index1 = Get_Permission_Index ("test-create-permission"), "Get_Permission_Index failed"); Add_Permission ("test-create-permission", Index2); T.Assert (Index2 = Index1, "Add_Permission failed"); end Test_Add_Permission; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is M : Security.Permissions.Permission_Manager; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Permissions.Permission_Manager; Perm : Permission_Type; User : Test_Principal; begin T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Permissions.Permission_Manager; Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Role_Type; Manager_Perm : Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); M.Add_Role_Type (Name => "admin", Result => Admin_Perm); M.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; P : constant URI_Permission (URI'Length) := URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URI_Permission (URI'Length) := URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Permissions.Permission_Manager; Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); Admin_Perm := M.Find_Role (Role); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); declare P : constant URI_Permission (URI'Length) := URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin_Perm) := True; T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Permissions.Tests;
----------------------------------------------------------------------- -- Security-permissions-tests - Unit tests for Security.Permissions -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; package body Security.Permissions.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Permissions"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Add_Permission", Test_Add_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index", Test_Add_Permission'Access); end Add_Tests; -- ------------------------------ -- Test Add_Permission and Get_Permission_Index -- ------------------------------ procedure Test_Add_Permission (T : in out Test) is Index1, Index2 : Permission_Index; begin Add_Permission ("test-create-permission", Index1); T.Assert (Index1 = Get_Permission_Index ("test-create-permission"), "Get_Permission_Index failed"); Add_Permission ("test-create-permission", Index2); T.Assert (Index2 = Index1, "Add_Permission failed"); end Test_Add_Permission; end Security.Permissions.Tests;
Remove the policy specific unit test
Remove the policy specific unit test
Ada
apache-2.0
Letractively/ada-security
6fbc0d1de669f0362e2bb9900256662387d6b57a
src/sqlite/ado-drivers-connections-sqlite.ads
src/sqlite/ado-drivers-connections-sqlite.ads
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; private with Ada.Containers.Doubly_Linked_Lists; package ADO.Drivers.Connections.Sqlite is subtype Sqlite3 is Sqlite3_H.sqlite3; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; URI : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); type SQLite_Database is record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; URI : Unbounded_String; end record; package Database_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => SQLite_Database); protected type Sqlite_Connections is procedure Open (Config : in Configuration'Class; Result : in out Ref.Ref'Class); procedure Clear; private List : Database_List.List; end Sqlite_Connections; type Sqlite_Driver is new ADO.Drivers.Connections.Driver with record Map : Sqlite_Connections; end record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. overriding procedure Create_Database (D : in out Sqlite_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); -- Deletes the SQLite driver. overriding procedure Finalize (D : in out Sqlite_Driver); end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; private with Ada.Containers.Doubly_Linked_Lists; package ADO.Drivers.Connections.Sqlite is -- Create database option. CREATE_NAME : constant String := "create"; subtype Sqlite3 is Sqlite3_H.sqlite3; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; URI : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); type SQLite_Database is record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; URI : Unbounded_String; end record; package Database_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => SQLite_Database); protected type Sqlite_Connections is procedure Open (Config : in Configuration'Class; Result : in out Ref.Ref'Class); procedure Clear; private List : Database_List.List; end Sqlite_Connections; type Sqlite_Driver is new ADO.Drivers.Connections.Driver with record Map : Sqlite_Connections; end record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. overriding procedure Create_Database (D : in out Sqlite_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); -- Deletes the SQLite driver. overriding procedure Finalize (D : in out Sqlite_Driver); end ADO.Drivers.Connections.Sqlite;
Declare the CREATE_NAME constant
Declare the CREATE_NAME constant
Ada
apache-2.0
stcarrez/ada-ado
bb5d2ca178c66630a679bea6f2aa9cdd91f69e41
src/asf-lifecycles.adb
src/asf-lifecycles.adb
----------------------------------------------------------------------- -- asf-lifecycles -- Lifecycle -- 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 ASF.Contexts.Exceptions; with ASF.Contexts.Flash; package body ASF.Lifecycles is -- ------------------------------ -- Initialize the the lifecycle handler. -- ------------------------------ procedure Initialize (Controller : in out Lifecycle; App : access ASF.Applications.Main.Application'Class) is begin -- Create the phase controllers. Lifecycle'Class (Controller).Create_Phase_Controllers; -- Initialize the phase controllers. for Phase in Controller.Controllers'Range loop Controller.Controllers (Phase).Initialize (App); end loop; end Initialize; -- ------------------------------ -- Finalize the lifecycle handler, freeing the allocated storage. -- ------------------------------ overriding procedure Finalize (Controller : in out Lifecycle) is procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class, Phase_Controller_Access); begin -- Free the phase controllers. for Phase in Controller.Controllers'Range loop Free (Controller.Controllers (Phase)); end loop; end Finalize; -- ------------------------------ -- Set the controller to be used for the given phase. -- ------------------------------ procedure Set_Controller (Controller : in out Lifecycle; Phase : in Phase_Type; Instance : in Phase_Controller_Access) is begin Controller.Controllers (Phase) := Instance; end Set_Controller; -- ------------------------------ -- Execute the lifecycle controller associated with the phase defined in <b>Phase</b>. -- Before processing, setup the faces context to update the current phase, then invoke -- the <b>Before_Phase</b> actions of the phase listeners. After execution of the controller -- invoke the <b>After_Phase</b> actions of the phase listeners. -- If an exception is raised, catch it and save it in the faces context. -- ------------------------------ procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class; Listeners : in Listener_Vectors.Ref; Phase : in Phase_Type) is use type ASF.Events.Phases.Phase_Type; use type ASF.Contexts.Exceptions.Exception_Handler_Access; -- Execute the before phase listener action. procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access); -- Execute the after phase listener action. procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access); Event : ASF.Events.Phases.Phase_Event (Phase); Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Context.Get_Flash; -- ------------------------------ -- Execute the before phase listener action. -- ------------------------------ procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase; begin if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then Listener.Before_Phase (Event); end if; exception when E : others => Context.Queue_Exception (E); end Before_Phase; -- ------------------------------ -- Execute the after phase listener action. -- ------------------------------ procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase; begin if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then Listener.After_Phase (Event); end if; exception when E : others => Context.Queue_Exception (E); end After_Phase; begin Context.Set_Current_Phase (Phase); Flash.Do_Pre_Phase_Actions (Phase, Context); -- Call the before phase listeners if there are some. Listeners.Iterate (Before_Phase'Access); begin Controller.Controllers (Phase).Execute (Context); exception when E : others => Context.Queue_Exception (E); end; Flash.Do_Post_Phase_Actions (Phase, Context); Listeners.Iterate (After_Phase'Access); -- If exceptions have been raised and queued during the current phase, process them. -- An exception handler could use them to redirect the current request to another -- page or navigate to a specific view. declare Ex : constant ASF.Contexts.Exceptions.Exception_Handler_Access := Context.Get_Exception_Handler; begin if Ex /= null then Ex.Handle; end if; end; end Execute; -- ------------------------------ -- Register a bundle and bind it to a facelet variable. -- ------------------------------ procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use ASF.Events.Phases; Listeners : constant Listener_Vectors.Ref := Controller.Listeners.Get; begin for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop if Context.Get_Render_Response or Context.Get_Response_Completed then return; end if; Controller.Execute (Context, Listeners, Phase); end loop; end Execute; -- ------------------------------ -- Render the response by executing the response phase. -- ------------------------------ procedure Render (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Listeners : constant Listener_Vectors.Ref := Controller.Listeners.Get; begin Controller.Execute (Context, Listeners, ASF.Events.Phases.RENDER_RESPONSE); end Render; -- ------------------------------ -- Add a phase listener in the lifecycle controller. -- ------------------------------ procedure Add_Phase_Listener (Controller : in out Lifecycle; Listener : in ASF.Events.Phases.Phase_Listener_Access) is begin Controller.Listeners.Append (Listener); end Add_Phase_Listener; -- ------------------------------ -- Remove a phase listener that was registered in the lifecycle controller. -- ------------------------------ procedure Remove_Phase_Listener (Controller : in out Lifecycle; Listener : in ASF.Events.Phases.Phase_Listener_Access) is begin Controller.Listeners.Remove (Listener); end Remove_Phase_Listener; end ASF.Lifecycles;
----------------------------------------------------------------------- -- asf-lifecycles -- Lifecycle -- Copyright (C) 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ASF.Contexts.Exceptions; with ASF.Contexts.Flash; package body ASF.Lifecycles is -- ------------------------------ -- Initialize the the lifecycle handler. -- ------------------------------ procedure Initialize (Controller : in out Lifecycle; Views : access ASF.Applications.Views.View_Handler'Class) is begin -- Create the phase controllers. Lifecycle'Class (Controller).Create_Phase_Controllers; -- Initialize the phase controllers. for Phase in Controller.Controllers'Range loop Controller.Controllers (Phase).Initialize (Views); end loop; end Initialize; -- ------------------------------ -- Finalize the lifecycle handler, freeing the allocated storage. -- ------------------------------ overriding procedure Finalize (Controller : in out Lifecycle) is procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class, Phase_Controller_Access); begin -- Free the phase controllers. for Phase in Controller.Controllers'Range loop Free (Controller.Controllers (Phase)); end loop; end Finalize; -- ------------------------------ -- Set the controller to be used for the given phase. -- ------------------------------ procedure Set_Controller (Controller : in out Lifecycle; Phase : in Phase_Type; Instance : in Phase_Controller_Access) is begin Controller.Controllers (Phase) := Instance; end Set_Controller; -- ------------------------------ -- Execute the lifecycle controller associated with the phase defined in <b>Phase</b>. -- Before processing, setup the faces context to update the current phase, then invoke -- the <b>Before_Phase</b> actions of the phase listeners. After execution of the controller -- invoke the <b>After_Phase</b> actions of the phase listeners. -- If an exception is raised, catch it and save it in the faces context. -- ------------------------------ procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class; Listeners : in Listener_Vectors.Ref; Phase : in Phase_Type) is use type ASF.Events.Phases.Phase_Type; use type ASF.Contexts.Exceptions.Exception_Handler_Access; -- Execute the before phase listener action. procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access); -- Execute the after phase listener action. procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access); Event : ASF.Events.Phases.Phase_Event (Phase); Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Context.Get_Flash; -- ------------------------------ -- Execute the before phase listener action. -- ------------------------------ procedure Before_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase; begin if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then Listener.Before_Phase (Event); end if; exception when E : others => Context.Queue_Exception (E); end Before_Phase; -- ------------------------------ -- Execute the after phase listener action. -- ------------------------------ procedure After_Phase (Listener : in ASF.Events.Phases.Phase_Listener_Access) is P : constant ASF.Events.Phases.Phase_Type := Listener.Get_Phase; begin if P = Event.Phase or P = ASF.Events.Phases.ANY_PHASE then Listener.After_Phase (Event); end if; exception when E : others => Context.Queue_Exception (E); end After_Phase; begin Context.Set_Current_Phase (Phase); Flash.Do_Pre_Phase_Actions (Phase, Context); -- Call the before phase listeners if there are some. Listeners.Iterate (Before_Phase'Access); begin Controller.Controllers (Phase).Execute (Context); exception when E : others => Context.Queue_Exception (E); end; Flash.Do_Post_Phase_Actions (Phase, Context); Listeners.Iterate (After_Phase'Access); -- If exceptions have been raised and queued during the current phase, process them. -- An exception handler could use them to redirect the current request to another -- page or navigate to a specific view. declare Ex : constant ASF.Contexts.Exceptions.Exception_Handler_Access := Context.Get_Exception_Handler; begin if Ex /= null then Ex.Handle; end if; end; end Execute; -- ------------------------------ -- Register a bundle and bind it to a facelet variable. -- ------------------------------ procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use ASF.Events.Phases; Listeners : constant Listener_Vectors.Ref := Controller.Listeners.Get; begin for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop if Context.Get_Render_Response or Context.Get_Response_Completed then return; end if; Controller.Execute (Context, Listeners, Phase); end loop; end Execute; -- ------------------------------ -- Render the response by executing the response phase. -- ------------------------------ procedure Render (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Listeners : constant Listener_Vectors.Ref := Controller.Listeners.Get; begin Controller.Execute (Context, Listeners, ASF.Events.Phases.RENDER_RESPONSE); end Render; -- ------------------------------ -- Add a phase listener in the lifecycle controller. -- ------------------------------ procedure Add_Phase_Listener (Controller : in out Lifecycle; Listener : in ASF.Events.Phases.Phase_Listener_Access) is begin Controller.Listeners.Append (Listener); end Add_Phase_Listener; -- ------------------------------ -- Remove a phase listener that was registered in the lifecycle controller. -- ------------------------------ procedure Remove_Phase_Listener (Controller : in out Lifecycle; Listener : in ASF.Events.Phases.Phase_Listener_Access) is begin Controller.Listeners.Remove (Listener); end Remove_Phase_Listener; end ASF.Lifecycles;
Use ASF.Applications.Views.View_Handler'Class for the lifecyle information to avoid a 'limited with' class for the ASF.Applications.Main package
Use ASF.Applications.Views.View_Handler'Class for the lifecyle information to avoid a 'limited with' class for the ASF.Applications.Main package
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
3b5afc78ee1eee21dcf515f469f311bc6e04fe61
src/asf-lifecycles.ads
src/asf-lifecycles.ads
----------------------------------------------------------------------- -- asf-lifecycles -- Lifecycle -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ASF.Events.Phases; with ASF.Contexts.Faces; with Util.Concurrent.Arrays; limited with ASF.Applications.Main; package ASF.Lifecycles is subtype Phase_Type is Events.Phases.Phase_Type range Events.Phases.RESTORE_VIEW .. Events.Phases.RENDER_RESPONSE; type Phase_Controller is abstract tagged limited private; type Phase_Controller_Access is access all Phase_Controller'Class; type Phase_Controller_Array is array (Phase_Type) of Phase_Controller_Access; -- Execute the phase. procedure Execute (Controller : in Phase_Controller; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Initialize the phase controller. procedure Initialize (Controller : in out Phase_Controller; App : access ASF.Applications.Main.Application'Class) is null; type Lifecycle is abstract new Ada.Finalization.Limited_Controlled with private; type Lifecycle_Access is access all Lifecycle'Class; -- Creates the phase controllers by invoking the <b>Set_Controller</b> -- procedure for each phase. This is called by <b>Initialize</b> to build -- the lifecycle handler. procedure Create_Phase_Controllers (Controller : in out Lifecycle) is abstract; -- Initialize the the lifecycle handler. procedure Initialize (Controller : in out Lifecycle; App : access ASF.Applications.Main.Application'Class); -- Finalize the lifecycle handler, freeing the allocated storage. overriding procedure Finalize (Controller : in out Lifecycle); -- Set the controller to be used for the given phase. procedure Set_Controller (Controller : in out Lifecycle; Phase : in Phase_Type; Instance : in Phase_Controller_Access); -- Register a bundle and bind it to a facelet variable. procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the response by executing the response phase. procedure Render (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Add a phase listener in the lifecycle controller. procedure Add_Phase_Listener (Controller : in out Lifecycle; Listener : in ASF.Events.Phases.Phase_Listener_Access); -- Remove a phase listener that was registered in the lifecycle controller. procedure Remove_Phase_Listener (Controller : in out Lifecycle; Listener : in ASF.Events.Phases.Phase_Listener_Access); private type Phase_Controller is abstract tagged limited null record; use type ASF.Events.Phases.Phase_Listener_Access; -- Use the concurrent arrays package so that we can insert phase listeners while -- we also have the lifecycle manager which invokes listeners for the existing requests. package Listener_Vectors is new Util.Concurrent.Arrays (Element_Type => ASF.Events.Phases.Phase_Listener_Access); -- Execute the lifecycle controller associated with the phase defined in <b>Phase</b>. -- Before processing, setup the faces context to update the current phase, then invoke -- the <b>Before_Phase</b> actions of the phase listeners. After execution of the controller -- invoke the <b>After_Phase</b> actions of the phase listeners. -- If an exception is raised, catch it and save it in the faces context. procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class; Listeners : in Listener_Vectors.Ref; Phase : in Phase_Type); type Lifecycle is abstract new Ada.Finalization.Limited_Controlled with record Controllers : Phase_Controller_Array; Listeners : Listener_Vectors.Vector; end record; end ASF.Lifecycles;
----------------------------------------------------------------------- -- asf-lifecycles -- Lifecycle -- Copyright (C) 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ASF.Events.Phases; with ASF.Contexts.Faces; with Util.Concurrent.Arrays; with ASF.Applications.Views; package ASF.Lifecycles is subtype Phase_Type is Events.Phases.Phase_Type range Events.Phases.RESTORE_VIEW .. Events.Phases.RENDER_RESPONSE; type Phase_Controller is abstract tagged limited private; type Phase_Controller_Access is access all Phase_Controller'Class; type Phase_Controller_Array is array (Phase_Type) of Phase_Controller_Access; -- Execute the phase. procedure Execute (Controller : in Phase_Controller; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Initialize the phase controller. procedure Initialize (Controller : in out Phase_Controller; Views : access ASF.Applications.Views.View_Handler'Class) is null; type Lifecycle is abstract new Ada.Finalization.Limited_Controlled with private; type Lifecycle_Access is access all Lifecycle'Class; -- Creates the phase controllers by invoking the <b>Set_Controller</b> -- procedure for each phase. This is called by <b>Initialize</b> to build -- the lifecycle handler. procedure Create_Phase_Controllers (Controller : in out Lifecycle) is abstract; -- Initialize the the lifecycle handler. procedure Initialize (Controller : in out Lifecycle; Views : access ASF.Applications.Views.View_Handler'Class); -- Finalize the lifecycle handler, freeing the allocated storage. overriding procedure Finalize (Controller : in out Lifecycle); -- Set the controller to be used for the given phase. procedure Set_Controller (Controller : in out Lifecycle; Phase : in Phase_Type; Instance : in Phase_Controller_Access); -- Register a bundle and bind it to a facelet variable. procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the response by executing the response phase. procedure Render (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Add a phase listener in the lifecycle controller. procedure Add_Phase_Listener (Controller : in out Lifecycle; Listener : in ASF.Events.Phases.Phase_Listener_Access); -- Remove a phase listener that was registered in the lifecycle controller. procedure Remove_Phase_Listener (Controller : in out Lifecycle; Listener : in ASF.Events.Phases.Phase_Listener_Access); private type Phase_Controller is abstract tagged limited null record; use type ASF.Events.Phases.Phase_Listener_Access; -- Use the concurrent arrays package so that we can insert phase listeners while -- we also have the lifecycle manager which invokes listeners for the existing requests. package Listener_Vectors is new Util.Concurrent.Arrays (Element_Type => ASF.Events.Phases.Phase_Listener_Access); -- Execute the lifecycle controller associated with the phase defined in <b>Phase</b>. -- Before processing, setup the faces context to update the current phase, then invoke -- the <b>Before_Phase</b> actions of the phase listeners. After execution of the controller -- invoke the <b>After_Phase</b> actions of the phase listeners. -- If an exception is raised, catch it and save it in the faces context. procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class; Listeners : in Listener_Vectors.Ref; Phase : in Phase_Type); type Lifecycle is abstract new Ada.Finalization.Limited_Controlled with record Controllers : Phase_Controller_Array; Listeners : Listener_Vectors.Vector; end record; end ASF.Lifecycles;
Use ASF.Applications.Views.View_Handler'Class for the lifecyle information to avoid a 'limited with' class for the ASF.Applications.Main package
Use ASF.Applications.Views.View_Handler'Class for the lifecyle information to avoid a 'limited with' class for the ASF.Applications.Main package
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
dc9789c462acd52705b51e4be7639f22bb5a591f
src/asf-applications-views.adb
src/asf-applications-views.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Responses; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then To_String (Handler.View_Ext) = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); if Facelets.Is_Null (Tree) then Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Responses; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then Handler.View_Ext = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); elsif Pos > 0 and then Handler.File_Ext = Name (Pos .. Name'Last) then return Name; end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); if Facelets.Is_Null (Tree) then Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
Fix Get_Facelet_Name to accept view names with the file extension
Fix Get_Facelet_Name to accept view names with the file extension
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
cc8ae6b1bd8b348540207d7dd50234b2c315a45b
src/wiki-helpers.adb
src/wiki-helpers.adb
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Wide_Wide_Characters.Handling; package body Wiki.Helpers is -- ------------------------------ -- Returns True if the character is a space or tab. -- ------------------------------ function Is_Space (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT; end Is_Space; -- ------------------------------ -- Returns True if the character is a space, tab or a newline. -- ------------------------------ function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Space_Or_Newline; -- ------------------------------ -- Returns True if the text is a valid URL -- ------------------------------ function Is_Url (Text : in Wiki.Strings.WString) return Boolean is begin if Text'Length <= 9 then return False; else return Text (Text'First .. Text'First + 6) = "http://" or Text (Text'First .. Text'First + 7) = "https://"; end if; end Is_Url; -- ------------------------------ -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. -- ------------------------------ function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean is S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext); begin return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg"; end Is_Image_Extension; -- ------------------------------ -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. -- ------------------------------ function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean is begin if No_End_Tag (Current_Tag) then return True; elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then return True; else case Current_Tag is when DT_TAG | DD_TAG => return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG; when TD_TAG => return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG; when TR_TAG => return False; when others => return False; end case; end if; end Need_Close; end Wiki.Helpers;
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Wide_Wide_Characters.Handling; package body Wiki.Helpers is -- ------------------------------ -- Returns True if the character is a space or tab. -- ------------------------------ function Is_Space (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT; end Is_Space; -- ------------------------------ -- Returns True if the character is a space, tab or a newline. -- ------------------------------ function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Space_Or_Newline; -- ------------------------------ -- Returns True if the character is a line terminator. -- ------------------------------ function Is_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Newline; -- ------------------------------ -- Returns True if the text is a valid URL -- ------------------------------ function Is_Url (Text : in Wiki.Strings.WString) return Boolean is begin if Text'Length <= 9 then return False; else return Text (Text'First .. Text'First + 6) = "http://" or Text (Text'First .. Text'First + 7) = "https://"; end if; end Is_Url; -- ------------------------------ -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. -- ------------------------------ function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean is S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext); begin return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg"; end Is_Image_Extension; -- ------------------------------ -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. -- ------------------------------ function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean is begin if No_End_Tag (Current_Tag) then return True; elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then return True; else case Current_Tag is when DT_TAG | DD_TAG => return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG; when TD_TAG => return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG; when TR_TAG => return False; when others => return False; end case; end if; end Need_Close; end Wiki.Helpers;
Implement the Is_Newline function
Implement the Is_Newline function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b63a27fc7b9c8d3a7180fa302821411f63e7739b
src/security-oauth-servers.ads
src/security-oauth-servers.ads
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- The OAuth 2.0 Authorization Framework. -- -- The authorization method produce a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Authorize (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identifies the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Manager; -- Auth : Security.Principal_Access; -- Token : String := ...; -- -- Realm.Authenticate (Token, Auth); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is abstract tagged limited private; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is abstract new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- The OAuth 2.0 Authorization Framework. -- -- The authorization method produce a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Authorize (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identifies the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Manager; -- Auth : Security.Principal_Access; -- Token : String := ...; -- -- Realm.Authenticate (Token, Auth); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is abstract tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is abstract new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
Declare Auth_Manager_Access
Declare Auth_Manager_Access
Ada
apache-2.0
stcarrez/ada-security
150b309ae77aa62871d172d5ebcf3860d10f5a41
src/security-oauth-servers.ads
src/security-oauth-servers.ads
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- The OAuth 2.0 Authorization Framework. -- -- The authorization method produce a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Authorize (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identifies the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Manager; -- Auth : Security.Principal_Access; -- Token : String := ...; -- -- Realm.Authenticate (Token, Auth); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- The OAuth 2.0 Authorization Framework. -- -- The authorization method produce a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Authorize (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identifies the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Auth : Security.Principal_Access; -- Token : String := ...; -- -- Realm.Authenticate (Token, Auth); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration := 3600.0; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
Set a default application expire timeout and update the documentation
Set a default application expire timeout and update the documentation
Ada
apache-2.0
stcarrez/ada-security
dff14477a9e14fa226cc6f0b796fdcc2e31dee28
regtests/util-http-clients-tests.ads
regtests/util-http-clients-tests.ads
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Tests.Servers; with Util.Streams.Texts; with Util.Streams.Sockets; package Util.Http.Clients.Tests is type Method_Type is (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH, CONNECT, UNKNOWN); type Test_Server is new Util.Tests.Servers.Server with record Method : Method_Type := UNKNOWN; Result : Ada.Strings.Unbounded.Unbounded_String; Content_Type : Ada.Strings.Unbounded.Unbounded_String; Length : Natural := 0; Test_Timeout : Boolean := False; end record; type Test_Server_Access is access all Test_Server'Class; -- Process the line received by the server. overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class); type Test is new Util.Tests.Test with record Server : Test_Server_Access := null; end record; -- Test the http Get operation. procedure Test_Http_Get (T : in out Test); -- Test the http POST operation. procedure Test_Http_Post (T : in out Test); -- Test the http PUT operation. procedure Test_Http_Put (T : in out Test); -- Test the http DELETE operation. procedure Test_Http_Delete (T : in out Test); -- Test the http OPTIONS operation. procedure Test_Http_Options (T : in out Test); -- Test the http PATCH operation. procedure Test_Http_Patch (T : in out Test); -- Test the http timeout. procedure Test_Http_Timeout (T : in out Test); overriding procedure Set_Up (T : in out Test); overriding procedure Tear_Down (T : in out Test); -- Get the test server base URI. function Get_Uri (T : in Test) return String; -- The <b>Http_Tests</b> package must be instantiated with one of the HTTP implementation. -- The <b>Register</b> procedure configures the Http.Client to use the given HTTP -- implementation before running the test. generic with procedure Register; NAME : in String; package Http_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Http_Test is new Test with null record; overriding procedure Set_Up (T : in out Http_Test); end Http_Tests; end Util.Http.Clients.Tests;
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Tests.Servers; with Util.Streams.Texts; with Util.Streams.Sockets; package Util.Http.Clients.Tests is type Method_Type is (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH, CONNECT, UNKNOWN); type Test_Server is new Util.Tests.Servers.Server with record Method : Method_Type := UNKNOWN; Result : Ada.Strings.Unbounded.Unbounded_String; Content_Type : Ada.Strings.Unbounded.Unbounded_String; Length : Natural := 0; Test_Timeout : Boolean := False; end record; type Test_Server_Access is access all Test_Server'Class; -- Process the line received by the server. overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class); type Test is new Util.Tests.Test with record Server : Test_Server_Access := null; end record; -- Test the http Get operation. procedure Test_Http_Get (T : in out Test); -- Test the http HEAD operation. procedure Test_Http_Head (T : in out Test); -- Test the http POST operation. procedure Test_Http_Post (T : in out Test); -- Test the http PUT operation. procedure Test_Http_Put (T : in out Test); -- Test the http DELETE operation. procedure Test_Http_Delete (T : in out Test); -- Test the http OPTIONS operation. procedure Test_Http_Options (T : in out Test); -- Test the http PATCH operation. procedure Test_Http_Patch (T : in out Test); -- Test the http timeout. procedure Test_Http_Timeout (T : in out Test); overriding procedure Set_Up (T : in out Test); overriding procedure Tear_Down (T : in out Test); -- Get the test server base URI. function Get_Uri (T : in Test) return String; -- The <b>Http_Tests</b> package must be instantiated with one of the HTTP implementation. -- The <b>Register</b> procedure configures the Http.Client to use the given HTTP -- implementation before running the test. generic with procedure Register; NAME : in String; package Http_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Http_Test is new Test with null record; overriding procedure Set_Up (T : in out Http_Test); end Http_Tests; end Util.Http.Clients.Tests;
Declare the Test_Http_Head procedure
Declare the Test_Http_Head procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
42f44cb446f9328cbbcc28aa923de2884fc6c03a
src/util-serialize-io-form.adb
src/util-serialize-io-form.adb
----------------------------------------------------------------------- -- swagger-streams-forms -- x-www-form-urlencoded streams -- 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.IO_Exceptions; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Util.Strings; with Util.Beans.Objects.Readers; package body Util.Serialize.IO.Form is use Ada.Strings.Unbounded; procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access) is begin Stream.Stream := Output; end Initialize; -- ------------------------------ -- Flush the buffer (if any) to the sink. -- ------------------------------ overriding procedure Flush (Stream : in out Output_Stream) is begin Stream.Stream.Flush; end Flush; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Output_Stream) is begin Stream.Stream.Close; end Close; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is begin Stream.Stream.Write (Buffer); end Write; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; procedure Write_Escape (Stream : in out Output_Stream; Value : in String) is begin for C of Value loop if C = ' ' then Stream.Stream.Write ('+'); elsif C >= 'a' and C <= 'z' then Stream.Stream.Write (C); elsif C >= 'A' and C <= 'Z' then Stream.Stream.Write (C); elsif C >= '0' and C <= '9' then Stream.Stream.Write (C); elsif C = '_' or C = '-' then Stream.Stream.Write (C); else Stream.Stream.Write ('%'); Stream.Stream.Write (Conversion (1 + (Character'Pos (C) / 16))); Stream.Stream.Write (Conversion (1 + (Character'Pos (C) mod 16))); end if; end loop; end Write_Escape; -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Write_Escape (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Write_Escape (Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode (Value)); end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Stream.Write (Util.Strings.Image (Value)); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Stream.Write (if Value then "true" else "false"); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Attribute; -- Write the attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String) is begin null; end Write_Null_Attribute; -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin Stream.Write_Wide_Attribute (Name, Value); end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin null; end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin null; end Write_Enum_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Entity; -- Write an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String) is begin null; end Write_Null_Entity; -- ------------------------------ -- Parse the stream using the form parser. -- ------------------------------ procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class; Sink : in out Reader'Class) is function From_Hex (C : in Character) return Natural; procedure Parse_Token (Into : out Ada.Strings.Unbounded.Unbounded_String); Name : Ada.Strings.Unbounded.Unbounded_String; Value : Ada.Strings.Unbounded.Unbounded_String; Last : Character; function From_Hex (C : in Character) return Natural is begin if C >= 'a' and C <= 'f' then return Character'Pos (C) - Character'Pos ('a') + 10; elsif C >= 'A' and C <= 'F' then return Character'Pos (C) - Character'Pos ('A') + 10; elsif C >= '0' and C <= '9' then return Character'Pos (C) - Character'Pos ('0'); else raise Parse_Error with "Invalid hexadecimal character: " & C; end if; end From_Hex; procedure Parse_Token (Into : out Ada.Strings.Unbounded.Unbounded_String) is C1, C2 : Character; begin Into := Ada.Strings.Unbounded.Null_Unbounded_String; loop Stream.Read (C1); if C1 = '&' or C1 = '=' then Last := C1; return; end if; if C1 = '+' then Ada.Strings.Unbounded.Append (Into, ' '); elsif C1 = '%' then Stream.Read (C1); Stream.Read (C2); Ada.Strings.Unbounded.Append (Into, Character'Val ((16 * From_Hex (C1)) + From_Hex (C2))); else Ada.Strings.Unbounded.Append (Into, C1); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Parse_Token; begin Sink.Start_Object ("", Handler); loop Parse_Token (Name); if Last /= '=' then raise Parse_Error with "Missing '=' after parameter name"; end if; Parse_Token (Value); Sink.Set_Member (To_String (Name), Util.Beans.Objects.To_Object (Value), Handler); if Stream.Is_Eof then Sink.Finish_Object ("", Handler); return; end if; if Last /= '&' then raise Parse_Error with "Missing '&' after parameter value"; end if; end loop; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return ""; end Get_Location; -- ------------------------------ -- Read a form file and return an object. -- ------------------------------ function Read (Path : in String) return Util.Beans.Objects.Object is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse (Path, R); return R.Get_Root; end Read; end Util.Serialize.IO.Form;
----------------------------------------------------------------------- -- swagger-streams-forms -- x-www-form-urlencoded streams -- 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.IO_Exceptions; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Util.Strings; with Util.Beans.Objects.Readers; package body Util.Serialize.IO.Form is use Ada.Strings.Unbounded; procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access) is begin Stream.Stream := Output; end Initialize; -- ------------------------------ -- Flush the buffer (if any) to the sink. -- ------------------------------ overriding procedure Flush (Stream : in out Output_Stream) is begin Stream.Stream.Flush; end Flush; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Output_Stream) is begin Stream.Stream.Close; end Close; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is begin Stream.Stream.Write (Buffer); end Write; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; procedure Write_Escape (Stream : in out Output_Stream; Value : in String) is begin for C of Value loop if C = ' ' then Stream.Stream.Write ('+'); elsif C >= 'a' and C <= 'z' then Stream.Stream.Write (C); elsif C >= 'A' and C <= 'Z' then Stream.Stream.Write (C); elsif C >= '0' and C <= '9' then Stream.Stream.Write (C); elsif C = '_' or C = '-' then Stream.Stream.Write (C); else Stream.Stream.Write ('%'); Stream.Stream.Write (Conversion (1 + (Character'Pos (C) / 16))); Stream.Stream.Write (Conversion (1 + (Character'Pos (C) mod 16))); end if; end loop; end Write_Escape; -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Write_Escape (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Write_Escape (Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode (Value)); end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Stream.Write (Util.Strings.Image (Value)); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Stream.Write (if Value then "true" else "false"); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Attribute; -- Write the attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String) is begin null; end Write_Null_Attribute; -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin Stream.Write_Wide_Attribute (Name, Value); end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin null; end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin null; end Write_Enum_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Entity; -- Write an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String) is begin null; end Write_Null_Entity; -- ------------------------------ -- Parse the stream using the form parser. -- ------------------------------ procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class; Sink : in out Reader'Class) is function From_Hex (C : in Character) return Natural; procedure Parse_Token (Into : out Ada.Strings.Unbounded.Unbounded_String); Name : Ada.Strings.Unbounded.Unbounded_String; Value : Ada.Strings.Unbounded.Unbounded_String; Last : Character; function From_Hex (C : in Character) return Natural is begin if C >= 'a' and C <= 'f' then return Character'Pos (C) - Character'Pos ('a') + 10; elsif C >= 'A' and C <= 'F' then return Character'Pos (C) - Character'Pos ('A') + 10; elsif C >= '0' and C <= '9' then return Character'Pos (C) - Character'Pos ('0'); else raise Parse_Error with "Invalid hexadecimal character: " & C; end if; end From_Hex; procedure Parse_Token (Into : out Ada.Strings.Unbounded.Unbounded_String) is C1, C2 : Character; begin Into := Ada.Strings.Unbounded.Null_Unbounded_String; loop Stream.Read (C1); if C1 = '&' or C1 = '=' then Last := C1; return; end if; if C1 = '+' then Ada.Strings.Unbounded.Append (Into, ' '); elsif C1 = '%' then Stream.Read (C1); Stream.Read (C2); Ada.Strings.Unbounded.Append (Into, Character'Val ((16 * From_Hex (C1)) + From_Hex (C2))); else Ada.Strings.Unbounded.Append (Into, C1); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Parse_Token; begin Sink.Start_Object ("", Handler); loop Parse_Token (Name); if Last /= '=' then raise Parse_Error with "Missing '=' after parameter name"; end if; Parse_Token (Value); Sink.Set_Member (To_String (Name), Util.Beans.Objects.To_Object (Value), Handler); if Stream.Is_Eof then Sink.Finish_Object ("", Handler); return; end if; if Last /= '&' then raise Parse_Error with "Missing '&' after parameter value"; end if; end loop; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is pragma Unreferenced (Handler); begin return ""; end Get_Location; -- ------------------------------ -- Read a form file and return an object. -- ------------------------------ function Read (Path : in String) return Util.Beans.Objects.Object is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse (Path, R); return R.Get_Root; end Read; end Util.Serialize.IO.Form;
Fix compilation warning in Get_Location
Fix compilation warning in Get_Location
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bd4cdee4a293d31c16fb4cc9731d2e9d1c7b4f9e
matp/src/events/mat-events-timelines.adb
matp/src/events/mat-events-timelines.adb
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Targets.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type); First_Event : MAT.Events.Targets.Probe_Event_Type; Last_Event : MAT.Events.Targets.Probe_Event_Type; Prev_Event : MAT.Events.Targets.Probe_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Targets.Event_Id_Type; procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > 500_000 then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.Start_Id := Event.Id; Info.Start_Time := Event.Time; end if; Info.End_Id := Event.Id; Info.End_Time := Event.Time; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.Start_Id := First_Event.Id; Info.Start_Time := First_Event.Time; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Targets.Probe_Event_Type; Max : in Positive; List : in out MAT.Events.Targets.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type); First_Id : MAT.Events.Targets.Event_Id_Type; Last_Id : MAT.Events.Targets.Event_Id_Type; First_Event : MAT.Events.Targets.Probe_Event_Type; Last_Event : MAT.Events.Targets.Probe_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type) is begin if Event.Index = MAT.Events.Targets.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type) is begin if Event.Index = MAT.Events.Targets.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.Targets.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Targets.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event); procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Targets.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Targets.Event_Info_Type) is pragma Unreferenced (Size); begin Info.Count := Info.Count + 1; Info.Last_Event := Event; end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.Targets.MSG_MALLOC and Event.Index /= MAT.Events.Targets.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Targets.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Targets.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Last_Event := Event; Info.Count := 1; Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; end MAT.Events.Timelines;
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Targets.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type); First_Event : MAT.Events.Targets.Probe_Event_Type; Last_Event : MAT.Events.Targets.Probe_Event_Type; Prev_Event : MAT.Events.Targets.Probe_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Targets.Event_Id_Type; procedure Collect (Event : in MAT.Events.Targets.Probe_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > 500_000 then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.Start_Id := Event.Id; Info.Start_Time := Event.Time; end if; Info.End_Id := Event.Id; Info.End_Time := Event.Time; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.Start_Id := First_Event.Id; Info.Start_Time := First_Event.Time; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Targets.Probe_Event_Type; Max : in Positive; List : in out MAT.Events.Targets.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type); First_Id : MAT.Events.Targets.Event_Id_Type; Last_Id : MAT.Events.Targets.Event_Id_Type; First_Event : MAT.Events.Targets.Probe_Event_Type; Last_Event : MAT.Events.Targets.Probe_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Targets.Probe_Event_Type) is begin if Event.Index = MAT.Events.Targets.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Targets.Probe_Event_Type) is begin if Event.Index = MAT.Events.Targets.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.Targets.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.Targets.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Targets.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event); procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Targets.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Targets.Event_Info_Type) is pragma Unreferenced (Size); begin Info.Count := Info.Count + 1; Info.Last_Event := Event; end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.Targets.MSG_MALLOC and Event.Index /= MAT.Events.Targets.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Targets.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Targets.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Last_Event := Event; Info.Count := 1; Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; -- ------------------------------ -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. -- ------------------------------ procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Natural; Frames : in out MAT.Events.Targets.Frame_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event); procedure Collect_Event (Event : in MAT.Events.Targets.Target_Event) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Targets.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Targets.Event_Info_Type) is pragma Unreferenced (Size); begin Info.Count := Info.Count + 1; Info.Last_Event := Event; end Update_Size; begin -- Look for events which are selected by the filter. if not Filter.Is_Selected (Event) then return; end if; declare Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame); begin for I in Backtrace'Range loop exit when I > Depth; declare Pos : constant MAT.Events.Targets.Frame_Event_Info_Cursor := Frames.Find (Backtrace (I)); begin if MAT.Events.Targets.Frame_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Frames.Update_Element (Pos, Update_Size'Access); else declare Info : Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Last_Event := Event; Info.Count := 1; Frames.Insert (Backtrace (I), Info); end; end if; end; end loop; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Frames; end MAT.Events.Timelines;
Implement the Find_Frames procedure to collect function addresses that perform directly or indirectly malloc/realloc/free calls
Implement the Find_Frames procedure to collect function addresses that perform directly or indirectly malloc/realloc/free calls
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c3922f8cfb0ffde0e6990adba2168b3279aaf6fd
src/asf-models-selects.ads
src/asf-models-selects.ads
----------------------------------------------------------------------- -- asf-models-selects -- Data model for UISelectOne and UISelectMany -- 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.Containers.Vectors; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Refs; package ASF.Models.Selects is -- ------------------------------ -- Select Item -- ------------------------------ -- The <b>Select_Item</b> type describes a single option of a list of options -- used by the <b>UISelectOne</b> or <b>UISelectMany</b> components. -- The select item contains: -- <ul> -- <li>A label -- <li>A value -- <li>A description -- <li>Whether the select item is disabled or not -- <li>Whether the label is escaped or not -- </ul> -- An application creates the <b>Select_Item</b> instances and passes them -- to the ASF components through an <b>Util.Beans.Objects.Object</b> value. type Select_Item is new Util.Beans.Basic.Readonly_Bean with private; type Select_Item_Access is access all Select_Item; -- Return an Object from the select item record. -- Returns a NULL object if the item is empty. function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object; -- Return the <b>Select_Item</b> instance from a generic bean object. -- Returns an empty item if the object does not hold a <b>Select_Item</b>. function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item (Label : in String; Value : in String; Description : in String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item_Wide (Label : in Wide_Wide_String; Value : in Wide_Wide_String; Description : in Wide_Wide_String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label, value and description. -- The objects are converted to a wide wide string. The empty string is used if they -- are null. function Create_Select_Item (Label : in Util.Beans.Objects.Object; Value : in Util.Beans.Objects.Object; Description : in Util.Beans.Objects.Object; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Get the item label. function Get_Label (Item : in Select_Item) return Wide_Wide_String; -- Get the item value. function Get_Value (Item : in Select_Item) return Wide_Wide_String; -- Get the item description. function Get_Description (Item : in Select_Item) return Wide_Wide_String; -- Returns true if the item is disabled. function Is_Disabled (Item : in Select_Item) return Boolean; -- Returns true if the label must be escaped using HTML escape rules. function Is_Escaped (Item : in Select_Item) return Boolean; -- Returns true if the select item component is empty. function Is_Empty (Item : in Select_Item) return Boolean; -- 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 Select_Item; Name : in String) return Util.Beans.Objects.Object; -- ------------------------------ -- Select Item List -- ------------------------------ -- The <b>Select_Item_List</b> type holds a list of <b>Select_Item</b>. -- Similar to <b>Select_Item</b>, an application builds the list items and gives it -- to the ASF components through an <b>Util.Beans.Objects.Object</b> instance. type Select_Item_List is new Util.Beans.Basic.List_Bean with private; type Select_Item_List_Access is access all Select_Item_List; -- Return an Object from the select item list. -- Returns a NULL object if the list is empty. function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object; -- Return the <b>Select_Item_List</b> instance from a generic bean object. -- Returns an empty list if the object does not hold a <b>Select_Item_List</b>. function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List; -- Get the number of elements in the list. overriding function Get_Count (From : in Select_Item_List) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out Select_Item_List; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in Select_Item_List) return Util.Beans.Objects.Object; -- Get the number of items in the list. function Length (List : in Select_Item_List) return Natural; -- Get the select item from the list function Get_Select_Item (List : in Select_Item_List'Class; Pos : in Positive) return Select_Item; -- Add the item at the end of the list. procedure Append (List : in out Select_Item_List; Item : in Select_Item'Class); -- Add the item at the end of the list. This is a shortcut for -- Append (Create_List_Item (Label, Value)) procedure Append (List : in out Select_Item_List; Label : in String; Value : in String); private use Ada.Strings.Wide_Wide_Unbounded; type Select_Item_Record is new Util.Refs.Ref_Entity with record Label : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; Description : Unbounded_Wide_Wide_String; Disabled : Boolean := False; Escape : Boolean := False; end record; type Select_Item_Record_Access is access all Select_Item_Record; package Select_Item_Refs is new Util.Refs.References (Element_Type => Select_Item_Record, Element_Access => Select_Item_Record_Access); type Select_Item is new Util.Beans.Basic.Readonly_Bean with record Item : Select_Item_Refs.Ref; end record; package Select_Item_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Select_Item); type Select_Item_Vector is new Util.Refs.Ref_Entity with record List : Select_Item_Vectors.Vector; end record; type Select_Item_Vector_Access is access all Select_Item_Vector; package Select_Item_Vector_Refs is new Util.Refs.References (Element_Type => Select_Item_Vector, Element_Access => Select_Item_Vector_Access); type Select_Item_List is new Util.Beans.Basic.List_Bean with record List : Select_Item_Vector_Refs.Ref; Current : aliased Select_Item; Row : Util.Beans.Objects.Object; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Select_Item_List; Name : in String) return Util.Beans.Objects.Object; end ASF.Models.Selects;
----------------------------------------------------------------------- -- asf-models-selects -- Data model for UISelectOne and UISelectMany -- Copyright (C) 2011, 2012, 2013, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; private with Util.Refs; package ASF.Models.Selects is -- ------------------------------ -- Select Item -- ------------------------------ -- The <b>Select_Item</b> type describes a single option of a list of options -- used by the <b>UISelectOne</b> or <b>UISelectMany</b> components. -- The select item contains: -- <ul> -- <li>A label -- <li>A value -- <li>A description -- <li>Whether the select item is disabled or not -- <li>Whether the label is escaped or not -- </ul> -- An application creates the <b>Select_Item</b> instances and passes them -- to the ASF components through an <b>Util.Beans.Objects.Object</b> value. type Select_Item is new Util.Beans.Basic.Readonly_Bean with private; type Select_Item_Access is access all Select_Item; -- Return an Object from the select item record. -- Returns a NULL object if the item is empty. function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object; -- Return the <b>Select_Item</b> instance from a generic bean object. -- Returns an empty item if the object does not hold a <b>Select_Item</b>. function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item (Label : in String; Value : in String; Description : in String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item_Wide (Label : in Wide_Wide_String; Value : in Wide_Wide_String; Description : in Wide_Wide_String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label, value and description. -- The objects are converted to a wide wide string. The empty string is used if they -- are null. function Create_Select_Item (Label : in Util.Beans.Objects.Object; Value : in Util.Beans.Objects.Object; Description : in Util.Beans.Objects.Object; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Get the item label. function Get_Label (Item : in Select_Item) return Wide_Wide_String; -- Get the item value. function Get_Value (Item : in Select_Item) return Wide_Wide_String; -- Get the item description. function Get_Description (Item : in Select_Item) return Wide_Wide_String; -- Returns true if the item is disabled. function Is_Disabled (Item : in Select_Item) return Boolean; -- Returns true if the label must be escaped using HTML escape rules. function Is_Escaped (Item : in Select_Item) return Boolean; -- Returns true if the select item component is empty. function Is_Empty (Item : in Select_Item) return Boolean; -- 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 Select_Item; Name : in String) return Util.Beans.Objects.Object; -- ------------------------------ -- Select Item List -- ------------------------------ -- The <b>Select_Item_List</b> type holds a list of <b>Select_Item</b>. -- Similar to <b>Select_Item</b>, an application builds the list items and gives it -- to the ASF components through an <b>Util.Beans.Objects.Object</b> instance. type Select_Item_List is new Util.Beans.Basic.List_Bean with private; type Select_Item_List_Access is access all Select_Item_List; -- Return an Object from the select item list. -- Returns a NULL object if the list is empty. function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object; -- Return the <b>Select_Item_List</b> instance from a generic bean object. -- Returns an empty list if the object does not hold a <b>Select_Item_List</b>. function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List; -- Get the number of elements in the list. overriding function Get_Count (From : in Select_Item_List) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out Select_Item_List; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in Select_Item_List) return Util.Beans.Objects.Object; -- Get the number of items in the list. function Length (List : in Select_Item_List) return Natural; -- Get the select item from the list function Get_Select_Item (List : in Select_Item_List'Class; Pos : in Positive) return Select_Item; -- Add the item at the end of the list. procedure Append (List : in out Select_Item_List; Item : in Select_Item'Class); -- Add the item at the end of the list. This is a shortcut for -- Append (Create_List_Item (Label, Value)) procedure Append (List : in out Select_Item_List; Label : in String; Value : in String); private use Ada.Strings.Wide_Wide_Unbounded; type Select_Item_Record is limited record Label : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; Description : Unbounded_Wide_Wide_String; Disabled : Boolean := False; Escape : Boolean := False; end record; type Select_Item_Record_Access is access all Select_Item_Record; package Select_Item_Refs is new Util.Refs.General_References (Element_Type => Select_Item_Record); subtype Select_Item_Record_Accessor is Select_Item_Refs.Element_Accessor; type Select_Item is new Util.Beans.Basic.Readonly_Bean with record Item : Select_Item_Refs.Ref; end record; package Select_Item_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Select_Item); type Select_Item_Vector is new Util.Refs.Ref_Entity with record List : Select_Item_Vectors.Vector; end record; type Select_Item_Vector_Access is access all Select_Item_Vector; package Select_Item_Vector_Refs is new Util.Refs.References (Element_Type => Select_Item_Vector, Element_Access => Select_Item_Vector_Access); type Select_Item_List is new Util.Beans.Basic.List_Bean with record List : Select_Item_Vector_Refs.Ref; Current : aliased Select_Item; Row : Util.Beans.Objects.Object; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Select_Item_List; Name : in String) return Util.Beans.Objects.Object; end ASF.Models.Selects;
Update to use General_References generic package
Update to use General_References generic package
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8afa69175635f41c795a93f5e140d7399e774d76
src/babel-stores-local.adb
src/babel-stores-local.adb
----------------------------------------------------------------------- -- bkp-stores-local -- Store management for local files -- Copyright (C) 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.Directories; with Ada.Strings.Unbounded; with Ada.Streams.Stream_IO; with Interfaces.C.Strings; with System.OS_Constants; with Util.Log.Loggers; with Util.Files; with Util.Systems.Os; with Util.Streams.Raw; with Util.Systems.Types; with Util.Systems.Os; with Interfaces; with Babel.Streams.Files; package body Babel.Stores.Local is function Errno return Integer; pragma Import (C, errno, "__get_errno"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Stores.Local"); function Get_File_Size (Ent : in Ada.Directories.Directory_Entry_Type) return Babel.Files.File_Size is Size : Ada.Directories.File_Size; begin Size := Ada.Directories.Size (Ent); return Babel.Files.File_Size (Size); exception when Constraint_Error => return Babel.Files.File_Size (Interfaces.Unsigned_32'Last); end Get_File_Size; -- ------------------------------ -- Get the absolute path to access the local file. -- ------------------------------ function Get_Absolute_Path (Store : in Local_Store_Type; Path : in String) return String is begin if Ada.Strings.Unbounded.Length (Store.Root_Dir) = 0 then return Path; else return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Store.Root_Dir), Path); end if; end Get_Absolute_Path; -- Open a file in the store to read its content with a stream. overriding procedure Open_File (Store : in out Local_Store_Type; Path : in String; Stream : out Babel.Streams.Stream_Access) is begin null; end Open_File; -- ------------------------------ -- Open a file in the store to read its content with a stream. -- ------------------------------ overriding procedure Read_File (Store : in out Local_Store_Type; Path : in String; Stream : out Babel.Streams.Refs.Stream_Ref) is Abs_Path : constant String := Store.Get_Absolute_Path (Path); File : Babel.Streams.Files.Stream_Access := new Babel.Streams.Files.Stream_Type; Buffer : Babel.Files.Buffers.Buffer_Access; begin Log.Info ("Read file {0}", Abs_Path); Stream := Babel.Streams.Refs.Stream_Refs.Create (File.all'Access); Store.Pool.Get_Buffer (Buffer); File.Open (Abs_Path, Buffer); end Read_File; -- ------------------------------ -- Write a file in the store with a stream. -- ------------------------------ overriding procedure Write_File (Store : in out Local_Store_Type; Path : in String; Stream : in Babel.Streams.Refs.Stream_Ref; Mode : in Babel.Files.File_Mode) is Abs_Path : constant String := Store.Get_Absolute_Path (Path); File : Babel.Streams.Files.Stream_Access := new Babel.Streams.Files.Stream_Type; Output : Babel.Streams.Refs.Stream_Ref; begin Log.Info ("Write file {0}", Abs_Path); Output := Babel.Streams.Refs.Stream_Refs.Create (File.all'Access); File.Create (Abs_Path, Mode); Babel.Streams.Refs.Copy (From => Stream, Into => Output); end Write_File; procedure Read (Store : in out Local_Store_Type; Path : in String; Into : in out Babel.Files.Buffers.Buffer) is use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; File : Ada.Streams.Stream_IO.File_Type; Abs_Path : constant String := Store.Get_Absolute_Path (Path); begin Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Abs_Path); Ada.Streams.Stream_IO.Read (File, Into.Data, Into.Last); Ada.Streams.Stream_IO.Close (File); Log.Info ("Read {0} -> {1}", Abs_Path, Ada.Streams.Stream_Element_Offset'Image (Into.Last)); end Read; procedure Open (Store : in out Local_Store_Type; Stream : in out Util.Streams.Raw.Raw_Stream; Path : in String) is use Util.Systems.Os; use type Interfaces.C.int; File : Util.Systems.Os.File_Type; Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path); begin File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#); if File < 0 then if Errno = System.OS_Constants.ENOENT then declare Dir : constant String := Ada.Directories.Containing_Directory (Path); begin Ada.Directories.Create_Path (Dir); end; File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#); end if; end if; if File < 0 then Log.Error ("Cannot create {0}", Path); raise Ada.Streams.Stream_IO.Name_Error with "Cannot create " & Path; end if; Stream.Initialize (File); Interfaces.C.Strings.Free (Name); end Open; procedure Write (Store : in out Local_Store_Type; Path : in String; Into : in Babel.Files.Buffers.Buffer) is use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; Abs_Path : constant String := Store.Get_Absolute_Path (Path); Stream : Util.Streams.Raw.Raw_Stream; begin Log.Info ("Write {0}", Abs_Path); Store.Open (Stream, Abs_Path); Stream.Write (Into.Data (Into.Data'First .. Into.Last)); Stream.Close; end Write; procedure Scan (Store : in out Local_Store_Type; Path : in String; Into : in out Babel.Files.File_Container'Class; Filter : in Babel.Filters.Filter_Type'Class) is use Ada.Directories; use type Babel.Files.File_Type; use type Babel.Files.Directory_Type; function Sys_Stat (Path : in System.Address; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "stat"); Search_Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True, Ada.Directories.Directory => True, Special_File => False); Search : Search_Type; Ent : Directory_Entry_Type; Stat : aliased Util.Systems.Types.Stat_Type; begin Log.Info ("Scan directory {0}", Path); Start_Search (Search, Directory => Path, Pattern => "*", Filter => Search_Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare use Util.Systems.Types; use Interfaces.C; use Babel.Files; Name : constant String := Simple_Name (Ent); Kind : constant File_Kind := Ada.Directories.Kind (Ent); File : Babel.Files.File_Type; Dir : Babel.Files.Directory_Type; Res : Integer; Fpath : String (1 .. Path'Length + Name'Length + 3); begin Fpath (Path'Range) := Path; Fpath (Path'Last + 1) := '/'; Fpath (Path'Last + 2 .. Path'Last + 2 + Name'Length - 1) := Name; Fpath (Path'Last + 2 + Name'Length) := ASCII.NUL; Res := Sys_Stat (Fpath'Address, Stat'Unchecked_Access); if (Stat.st_mode and S_IFMT) = S_IFREG then if Filter.Is_Accepted (Kind, Path, Name) then File := Into.Find (Name); if File = Babel.Files.NO_FILE then File := Into.Create (Name); end if; Babel.Files.Set_Size (File, Babel.Files.File_Size (Stat.st_size)); Babel.Files.Set_Owner (File, Uid_Type (Stat.st_uid), Gid_Type (Stat.st_gid)); Babel.Files.Set_Date (File, Stat.st_mtim); Log.Debug ("Adding {0}", Name); Into.Add_File (File); end if; elsif Name /= "." and Name /= ".." and Filter.Is_Accepted (Kind, Path, Name) then Dir := Into.Find (Name); if Dir = Babel.Files.NO_DIRECTORY then Dir := Into.Create (Name); end if; Into.Add_Directory (Dir); end if; end; end loop; exception when E : others => Log.Error ("Exception ", E); end Scan; -- ------------------------------ -- Set the root directory for the local store. -- ------------------------------ procedure Set_Root_Directory (Store : in out Local_Store_Type; Path : in String) is begin Store.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Path); end Set_Root_Directory; -- ------------------------------ -- Set the buffer pool to be used by local store. -- ------------------------------ procedure Set_Buffers (Store : in out Local_Store_Type; Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is begin Store.Pool := Buffers; end Set_Buffers; end Babel.Stores.Local;
----------------------------------------------------------------------- -- bkp-stores-local -- Store management for local files -- Copyright (C) 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.Directories; with Ada.Strings.Unbounded; with Ada.Streams.Stream_IO; with Interfaces.C.Strings; with System.OS_Constants; with Util.Log.Loggers; with Util.Files; with Util.Systems.Os; with Util.Streams.Raw; with Util.Systems.Types; with Util.Systems.Os; with Interfaces; with Babel.Streams.Files; package body Babel.Stores.Local is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Stores.Local"); function Get_File_Size (Ent : in Ada.Directories.Directory_Entry_Type) return Babel.Files.File_Size is Size : Ada.Directories.File_Size; begin Size := Ada.Directories.Size (Ent); return Babel.Files.File_Size (Size); exception when Constraint_Error => return Babel.Files.File_Size (Interfaces.Unsigned_32'Last); end Get_File_Size; -- ------------------------------ -- Get the absolute path to access the local file. -- ------------------------------ function Get_Absolute_Path (Store : in Local_Store_Type; Path : in String) return String is begin if Ada.Strings.Unbounded.Length (Store.Root_Dir) = 0 then return Path; else return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Store.Root_Dir), Path); end if; end Get_Absolute_Path; -- Open a file in the store to read its content with a stream. overriding procedure Open_File (Store : in out Local_Store_Type; Path : in String; Stream : out Babel.Streams.Stream_Access) is begin null; end Open_File; -- ------------------------------ -- Open a file in the store to read its content with a stream. -- ------------------------------ overriding procedure Read_File (Store : in out Local_Store_Type; Path : in String; Stream : out Babel.Streams.Refs.Stream_Ref) is Abs_Path : constant String := Store.Get_Absolute_Path (Path); File : Babel.Streams.Files.Stream_Access := new Babel.Streams.Files.Stream_Type; Buffer : Babel.Files.Buffers.Buffer_Access; begin Log.Info ("Read file {0}", Abs_Path); Stream := Babel.Streams.Refs.Stream_Refs.Create (File.all'Access); Store.Pool.Get_Buffer (Buffer); File.Open (Abs_Path, Buffer); end Read_File; -- ------------------------------ -- Write a file in the store with a stream. -- ------------------------------ overriding procedure Write_File (Store : in out Local_Store_Type; Path : in String; Stream : in Babel.Streams.Refs.Stream_Ref; Mode : in Babel.Files.File_Mode) is Abs_Path : constant String := Store.Get_Absolute_Path (Path); File : Babel.Streams.Files.Stream_Access := new Babel.Streams.Files.Stream_Type; Output : Babel.Streams.Refs.Stream_Ref; begin Log.Info ("Write file {0}", Abs_Path); Output := Babel.Streams.Refs.Stream_Refs.Create (File.all'Access); File.Create (Abs_Path, Mode); Babel.Streams.Refs.Copy (From => Stream, Into => Output); end Write_File; procedure Read (Store : in out Local_Store_Type; Path : in String; Into : in out Babel.Files.Buffers.Buffer) is use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; File : Ada.Streams.Stream_IO.File_Type; Abs_Path : constant String := Store.Get_Absolute_Path (Path); begin Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Abs_Path); Ada.Streams.Stream_IO.Read (File, Into.Data, Into.Last); Ada.Streams.Stream_IO.Close (File); Log.Info ("Read {0} -> {1}", Abs_Path, Ada.Streams.Stream_Element_Offset'Image (Into.Last)); end Read; procedure Open (Store : in out Local_Store_Type; Stream : in out Util.Streams.Raw.Raw_Stream; Path : in String) is use Util.Systems.Os; use type Interfaces.C.int; File : Util.Systems.Os.File_Type; Name : Util.Systems.Os.Ptr := Interfaces.C.Strings.New_String (Path); begin File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#); if File < 0 then if Errno = System.OS_Constants.ENOENT then declare Dir : constant String := Ada.Directories.Containing_Directory (Path); begin Ada.Directories.Create_Path (Dir); end; File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, 8#644#); end if; end if; if File < 0 then Log.Error ("Cannot create {0}", Path); raise Ada.Streams.Stream_IO.Name_Error with "Cannot create " & Path; end if; Stream.Initialize (File); Interfaces.C.Strings.Free (Name); end Open; procedure Write (Store : in out Local_Store_Type; Path : in String; Into : in Babel.Files.Buffers.Buffer) is use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; Abs_Path : constant String := Store.Get_Absolute_Path (Path); Stream : Util.Streams.Raw.Raw_Stream; begin Log.Info ("Write {0}", Abs_Path); Store.Open (Stream, Abs_Path); Stream.Write (Into.Data (Into.Data'First .. Into.Last)); Stream.Close; end Write; procedure Scan (Store : in out Local_Store_Type; Path : in String; Into : in out Babel.Files.File_Container'Class; Filter : in Babel.Filters.Filter_Type'Class) is use Ada.Directories; use type Babel.Files.File_Type; use type Babel.Files.Directory_Type; function Sys_Stat (Path : in System.Address; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "stat"); Search_Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True, Ada.Directories.Directory => True, Special_File => False); Search : Search_Type; Ent : Directory_Entry_Type; Stat : aliased Util.Systems.Types.Stat_Type; begin Log.Info ("Scan directory {0}", Path); Start_Search (Search, Directory => Path, Pattern => "*", Filter => Search_Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare use Util.Systems.Types; use Interfaces.C; use Babel.Files; Name : constant String := Simple_Name (Ent); Kind : constant File_Kind := Ada.Directories.Kind (Ent); File : Babel.Files.File_Type; Dir : Babel.Files.Directory_Type; Res : Integer; Fpath : String (1 .. Path'Length + Name'Length + 3); begin Fpath (Path'Range) := Path; Fpath (Path'Last + 1) := '/'; Fpath (Path'Last + 2 .. Path'Last + 2 + Name'Length - 1) := Name; Fpath (Path'Last + 2 + Name'Length) := ASCII.NUL; Res := Sys_Stat (Fpath'Address, Stat'Unchecked_Access); if (Stat.st_mode and S_IFMT) = S_IFREG then if Filter.Is_Accepted (Kind, Path, Name) then File := Into.Find (Name); if File = Babel.Files.NO_FILE then File := Into.Create (Name); end if; Babel.Files.Set_Size (File, Babel.Files.File_Size (Stat.st_size)); Babel.Files.Set_Owner (File, Uid_Type (Stat.st_uid), Gid_Type (Stat.st_gid)); Babel.Files.Set_Date (File, Stat.st_mtim); Log.Debug ("Adding {0}", Name); Into.Add_File (File); end if; elsif Name /= "." and Name /= ".." and Filter.Is_Accepted (Kind, Path, Name) then Dir := Into.Find (Name); if Dir = Babel.Files.NO_DIRECTORY then Dir := Into.Create (Name); end if; Into.Add_Directory (Dir); end if; end; end loop; exception when E : others => Log.Error ("Exception ", E); end Scan; -- ------------------------------ -- Set the root directory for the local store. -- ------------------------------ procedure Set_Root_Directory (Store : in out Local_Store_Type; Path : in String) is begin Store.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Path); end Set_Root_Directory; -- ------------------------------ -- Set the buffer pool to be used by local store. -- ------------------------------ procedure Set_Buffers (Store : in out Local_Store_Type; Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is begin Store.Pool := Buffers; end Set_Buffers; end Babel.Stores.Local;
Remove declaration of Errno function
Remove declaration of Errno function
Ada
apache-2.0
stcarrez/babel
be9a9728430116a86d19c25066ecb7558cc7164b
src/gen-model-mappings.adb
src/gen-model-mappings.adb
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- 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 Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER or From.Kind = T_ENTITY_TYPE); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); elsif Name = "isNullable" then return Util.Beans.Objects.To_Object (From.Nullable); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the type name. -- ------------------------------ function Get_Type_Name (From : Mapping_Definition) return String is begin case From.Kind is when T_BOOLEAN => return "boolean"; when T_INTEGER => return "integer"; when T_DATE => return "date"; when T_IDENTIFIER => return "identifier"; when T_STRING => return "string"; when T_ENTITY_TYPE => return "entity_type"; when T_BLOB => return "blob"; when T_ENUM => return From.Get_Name; when others => return From.Get_Name; end case; end Get_Type_Name; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Mapping.Set_Name (From); Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; Mapping.Allow_Null.Nullable := True; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- 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 Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER or From.Kind = T_ENTITY_TYPE); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); elsif Name = "isNullable" then return Util.Beans.Objects.To_Object (From.Nullable); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the type name. -- ------------------------------ function Get_Type_Name (From : Mapping_Definition) return String is begin case From.Kind is when T_BOOLEAN => return "boolean"; when T_INTEGER => return "integer"; when T_DATE => return "date"; when T_IDENTIFIER => return "identifier"; when T_STRING => return "string"; when T_ENTITY_TYPE => return "entity_type"; when T_BLOB => return "blob"; when T_ENUM => return From.Get_Name; when others => return From.Get_Name; end case; end Get_Type_Name; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; -- ------------------------------ -- Get the type name according to the mapping definition. -- ------------------------------ function Get_Type_Name (Name : in Ada.Strings.Unbounded.Unbounded_String) return String is T : constant Mapping_Definition_Access := Find_Type (Name, False); begin if T = null then return To_String (Name); else return To_String (T.Target); end if; end Get_Type_Name; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Mapping.Set_Name (From); Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; Mapping.Allow_Null.Nullable := True; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
Implement Get_Type_Name function
Implement Get_Type_Name function
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
d4001b9ad7cc8aed14c09aa3124e884cc86e51f5
src/el-expressions.ads
src/el-expressions.ads
----------------------------------------------------------------------- -- EL.Expressions -- Expression Language -- 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. ----------------------------------------------------------------------- -- -- First, create the expression object: -- -- E : constant Expression := EL.Expressions.Create_Expression ("obj.count + 3"); -- -- The expression must be evaluated against an expression context. -- The expression context will resolve variables whose values can change depending -- on the evaluation context. In the example, ''obj'' is the variable name -- and ''count'' is the property associated with that variable. -- -- Value : constant Object := E.Get_Value (Context); -- -- The ''Value'' holds the result which can be a boolean, an integer, a date, -- a float number or a string. The value can be converted as follows: -- -- N : Integer := To_Integer (Value); -- with EL.Objects; with Ada.Finalization; limited with EL.Expressions.Nodes; with EL.Contexts; with EL.Beans; package EL.Expressions is use EL.Objects; use EL.Contexts; -- Exception raised when parsing an invalid expression. Invalid_Expression : exception; -- Exception raised when a variable cannot be resolved. Invalid_Variable : exception; -- ------------------------------ -- Expression -- ------------------------------ type Expression is new Ada.Finalization.Controlled with private; -- Get the value of the expression using the given expression context. -- Returns an object that holds a typed result. function Get_Value (Expr : Expression; Context : ELContext'Class) return Object; -- Parse an expression and return its representation ready for evaluation. -- The context is used to resolve the functions. Variables will be -- resolved during evaluation of the expression. -- Raises <b>Invalid_Expression</b> if the expression is invalid. function Create_Expression (Expr : String; Context : ELContext'Class) return Expression; -- ------------------------------ -- ValueExpression -- ------------------------------ -- type ValueExpression is new Expression with private; type ValueExpression_Access is access all ValueExpression'Class; -- Get the value of the expression using the given expression context. -- Returns an object that holds a typed result. overriding function Get_Value (Expr : in ValueExpression; Context : in ELContext'Class) return Object; procedure Set_Value (Expr : in ValueExpression; Context : in ELContext'Class; Value : in Object); function Is_Readonly (Expr : in ValueExpression) return Boolean; -- Parse an expression and return its representation ready for evaluation. function Create_Expression (Expr : String; Context : ELContext'Class) return ValueExpression; function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class) return ValueExpression; private procedure Adjust (Object : in out Expression); procedure Finalize (Object : in out Expression); type Expression is new Ada.Finalization.Controlled with record Node : access EL.Expressions.Nodes.ELNode'Class; end record; type ValueExpression is new Expression with record Bean : access EL.Beans.Readonly_Bean'Class; end record; end EL.Expressions;
----------------------------------------------------------------------- -- EL.Expressions -- Expression Language -- 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. ----------------------------------------------------------------------- -- -- First, create the expression object: -- -- E : constant Expression := EL.Expressions.Create_Expression ("obj.count + 3"); -- -- The expression must be evaluated against an expression context. -- The expression context will resolve variables whose values can change depending -- on the evaluation context. In the example, ''obj'' is the variable name -- and ''count'' is the property associated with that variable. -- -- Value : constant Object := E.Get_Value (Context); -- -- The ''Value'' holds the result which can be a boolean, an integer, a date, -- a float number or a string. The value can be converted as follows: -- -- N : Integer := To_Integer (Value); -- with EL.Objects; with Ada.Finalization; limited with EL.Expressions.Nodes; with EL.Contexts; with EL.Beans; package EL.Expressions is use EL.Objects; use EL.Contexts; -- Exception raised when parsing an invalid expression. Invalid_Expression : exception; -- Exception raised when a variable cannot be resolved. Invalid_Variable : exception; -- ------------------------------ -- Expression -- ------------------------------ type Expression is new Ada.Finalization.Controlled with private; type Expression_Access is access all Expression'Class; -- Get the value of the expression using the given expression context. -- Returns an object that holds a typed result. function Get_Value (Expr : Expression; Context : ELContext'Class) return Object; -- Parse an expression and return its representation ready for evaluation. -- The context is used to resolve the functions. Variables will be -- resolved during evaluation of the expression. -- Raises <b>Invalid_Expression</b> if the expression is invalid. function Create_Expression (Expr : String; Context : ELContext'Class) return Expression; -- ------------------------------ -- ValueExpression -- ------------------------------ -- type ValueExpression is new Expression with private; type ValueExpression_Access is access all ValueExpression'Class; -- Get the value of the expression using the given expression context. -- Returns an object that holds a typed result. overriding function Get_Value (Expr : in ValueExpression; Context : in ELContext'Class) return Object; procedure Set_Value (Expr : in ValueExpression; Context : in ELContext'Class; Value : in Object); function Is_Readonly (Expr : in ValueExpression) return Boolean; -- Parse an expression and return its representation ready for evaluation. function Create_Expression (Expr : String; Context : ELContext'Class) return ValueExpression; function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class) return ValueExpression; private procedure Adjust (Object : in out Expression); procedure Finalize (Object : in out Expression); type Expression is new Ada.Finalization.Controlled with record Node : access EL.Expressions.Nodes.ELNode'Class; end record; type ValueExpression is new Expression with record Bean : access EL.Beans.Readonly_Bean'Class; end record; end EL.Expressions;
Declare Expression_Access
Declare Expression_Access
Ada
apache-2.0
Letractively/ada-el
2ece7a422bc46d553f59554f04ecc43cc063478b
src/wiki-attributes.adb
src/wiki-attributes.adb
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Ada.Unchecked_Deallocation; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Attr.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return To_Unbounded_Wide_Wide_String (Attr.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List_Type; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Access := Attribute_Vectors.Element (Iter); begin if Attr.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Unbounded_Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Null_Unbounded_Wide_Wide_String; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String) is Attr : constant Attribute_Access := new Attribute '(Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attr); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name), Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List_Type) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List_Type) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List_Type) is procedure Free is new Ada.Unchecked_Deallocation (Object => Attribute, Name => Attribute_Access); Item : Attribute_Access; begin while not List.List.Is_Empty loop Item := List.List.Last_Element; List.List.Delete_Last; Free (Item); end loop; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List_Type; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Access; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Name, Item.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List_Type) is begin List.Clear; end Finalize; end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Ada.Unchecked_Deallocation; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Attr.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return To_Unbounded_Wide_Wide_String (Attr.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List_Type; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Access := Attribute_Vectors.Element (Iter); begin if Attr.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Unbounded_Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Null_Unbounded_Wide_Wide_String; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String) is Attr : constant Attribute_Access := new Attribute '(Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attr); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name), Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Val : constant Wide_Wide_String := To_Wide_Wide_String (Value); Attr : constant Attribute_Access := new Attribute '(Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attr); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List_Type) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List_Type) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List_Type) is procedure Free is new Ada.Unchecked_Deallocation (Object => Attribute, Name => Attribute_Access); Item : Attribute_Access; begin while not List.List.Is_Empty loop Item := List.List.Last_Element; List.List.Delete_Last; Free (Item); end loop; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List_Type; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Access; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Name, Item.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List_Type) is begin List.Clear; end Finalize; end Wiki.Attributes;
Implement new Append procedure
Implement new Append procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
8512d236517dd6e7bb7771fea23d5264dddc4987
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.Finalization; with Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Log.Loggers; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; with Security.Permissions; with Security.Controllers; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Positive'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); -- package Role_Config is -- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); -- pragma Warnings (Off, Role_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Positive'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
stcarrez/ada-security
e3b7525b1578161f89be21014111c1e61237b4f1
src/util-processes.adb
src/util-processes.adb
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.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); -- ------------------------------ -- 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; -- ------------------------------ -- 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; -- ------------------------------ -- 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) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Proc.Sys := new Util.Processes.Os.System_Process; -- Build the argc/argv table, terminate by NULL for I in Arguments'Range loop Proc.Sys.Append_Argument (Arguments (I).all); end loop; -- Prepare to redirect the input/output/error streams. 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); -- System specific spawn Proc.Exit_Value := -1; Proc.Sys.Spawn (Proc); 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 Pos : Natural := Command'First; N : Natural; begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Proc.Sys := new Util.Processes.Os.System_Process; 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 -- 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 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); -- 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); end Finalize; end Util.Processes;
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- Copyright (C) 2011, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- 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; -- ------------------------------ -- 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) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Proc.Sys := new Util.Processes.Os.System_Process; -- Build the argc/argv table, terminate by NULL for I in Arguments'Range loop Proc.Sys.Append_Argument (Arguments (I).all); end loop; -- Prepare to redirect the input/output/error streams. 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); 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 Pos : Natural := Command'First; N : Natural; begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Proc.Sys := new Util.Processes.Os.System_Process; 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 -- 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 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;
Implement Add_Close procedure Update call to Set_Streams Free the To_Close array
Implement Add_Close procedure Update call to Set_Streams Free the To_Close array
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
47108ee9c22a8074fa44462803bd5f8b15355dec
src/wiki-documents.adb
src/wiki-documents.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; -- ------------------------------ -- Append a HTML tag start node to the document. -- ------------------------------ procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0)); end case; end Append; -- ------------------------------ -- Append the text with the given format at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST, Len => 0, Level => Level, others => <>)); end if; end Add_List_Item; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Into : in out Document; Level : in Natural) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Level => Level, others => <>)); end Add_Blockquote; -- Add a text block that is pre-formatted. procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Preformatted => Text, others => <>)); end Add_Preformatted; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Node_List_Ref) is begin if Wiki.Nodes.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref is begin return Doc.TOC; end Get_TOC; end Wiki.Documents;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; -- ------------------------------ -- Append a HTML tag start node to the document. -- ------------------------------ procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0)); end case; end Append; -- ------------------------------ -- Append the text with the given format at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST, Len => 0, Level => Level, others => <>)); end if; end Add_List_Item; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Into : in out Document; Level : in Natural) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Level => Level, others => <>)); end Add_Blockquote; -- Add a text block that is pre-formatted. procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Preformatted => Text, others => <>)); end Add_Preformatted; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Returns True if the document is empty. -- ------------------------------ function Is_Empty (Doc : in Document) return Boolean is begin return Wiki.Nodes.Is_Empty (Doc.Nodes); end Is_Empty; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Node_List_Ref) is begin if Wiki.Nodes.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref is begin return Doc.TOC; end Get_TOC; end Wiki.Documents;
Implement the Is_Empty function
Implement the Is_Empty function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
468fd1cb64a551461a4e5b72fc52959bc69ce939
src/wiki-render-html.ads
src/wiki-render-html.ads
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Add a section header in the document. procedure Add_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Document : in out Html_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. procedure Add_Text (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); procedure Start_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Html_Renderer); private procedure Close_Paragraph (Document : in out Html_Renderer); procedure Open_Paragraph (Document : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Add a section header in the document. procedure Add_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Document : in out Html_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); procedure Start_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Html_Renderer); private procedure Close_Paragraph (Document : in out Html_Renderer); procedure Open_Paragraph (Document : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); end Wiki.Render.Html;
Declare the Render_Tag procedure
Declare the Render_Tag procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
00b1df989be5d23f10d50d420944fcfce2ef83d6
awa/regtests/awa-wikis-parsers-tests.adb
awa/regtests/awa-wikis-parsers-tests.adb
----------------------------------------------------------------------- -- awa-wikis-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with AWA.Wikis.Writers; package body AWA.Wikis.Parsers.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Parsers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (bold)", Test_Wiki_Bold'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (italic)", Test_Wiki_Italic'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (italic, bold)", Test_Wiki_Formats'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (headings)", Test_Wiki_Section'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (lists)", Test_Wiki_List'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (links)", Test_Wiki_Link'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (quote)", Test_Wiki_Quote'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (line break)", Test_Wiki_Line_Break'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (image)", Test_Wiki_Image'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (preformatted)", Test_Wiki_Preformatted'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Text.Renderer", Test_Wiki_Text_Renderer'Access); end Add_Tests; -- ------------------------------ -- Test bold rendering. -- ------------------------------ procedure Test_Wiki_Bold (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>", Writers.To_Html ("*bold*", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Writers.To_Html ("x *bold* y", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>", Writers.To_Html ("x *bold y", SYNTAX_MIX), "Bold rendering invalid (MIX)"); Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>", Writers.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>", Writers.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR), "No bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Writers.To_Html ("x '''bold''' y", SYNTAX_PHPBB), "Bold rendering invalid (PHPBB)"); end Test_Wiki_Bold; -- ------------------------------ -- Test italic rendering. -- ------------------------------ procedure Test_Wiki_Italic (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>item</i></p>", Writers.To_Html ("_item_", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Writers.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Writers.To_Html ("x _item y", SYNTAX_MIX), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Writers.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Writers.To_Html ("x ''item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>", Writers.To_Html ("x 'item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); end Test_Wiki_Italic; -- ------------------------------ -- Test various format rendering. -- ------------------------------ procedure Test_Wiki_Formats (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>", Writers.To_Html ("_it*bold*em_", SYNTAX_GOOGLE), "Italic+Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Writers.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Writers.To_Html ("x _item y", SYNTAX_GOOGLE), "Italic rendering invalid"); end Test_Wiki_Formats; -- ------------------------------ -- Test heading rendering. -- ------------------------------ procedure Test_Wiki_Section (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<h1>item</h1>", Writers.To_Html ("= item =", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h2>item</h2>", Writers.To_Html ("== item == ", SYNTAX_GOOGLE), "H2 rendering invalid"); Util.Tests.Assert_Equals (T, "<h3>item</h3>", Writers.To_Html ("=== item === ", SYNTAX_GOOGLE), "H3 rendering invalid"); Util.Tests.Assert_Equals (T, "<h4>item</h4>", Writers.To_Html ("==== item ==== ", SYNTAX_GOOGLE), "H4 rendering invalid"); Util.Tests.Assert_Equals (T, "<h5>item</h5>", Writers.To_Html ("===== item =====", SYNTAX_GOOGLE), "H5 rendering invalid"); Util.Tests.Assert_Equals (T, "<h6>item</h6>", Writers.To_Html ("====== item ===", SYNTAX_GOOGLE), "H6 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>", Writers.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>", Writers.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =", SYNTAX_GOOGLE), "H1 rendering invalid"); end Test_Wiki_Section; -- ------------------------------ -- Test list rendering. -- ------------------------------ procedure Test_Wiki_List (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>", Writers.To_Html ("# item", SYNTAX_GOOGLE), "Ordered list rendering invalid"); Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF & "</li><li>item2 item2" & ASCII.LF & "</li><li><ol>item3</li></ol></ol>", Writers.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3", SYNTAX_GOOGLE), "Ordered rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Writers.To_Html (" * item", SYNTAX_GOOGLE), "Bullet list rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Writers.To_Html ("* item", SYNTAX_DOTCLEAR), "Bullet list rendering invalid"); end Test_Wiki_List; -- ------------------------------ -- Test link rendering. -- ------------------------------ procedure Test_Wiki_Link (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>", Writers.To_Html ("[name]", SYNTAX_GOOGLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a title=""some"" lang=""en"" " & "href=""http://www.joe.com/item"">name </a></p>", Writers.To_Html ("[name |http://www.joe.com/item|en|some]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>", Writers.To_Html ("[[name]]", SYNTAX_CREOLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p>[d</p>", Writers.To_Html ("[d", SYNTAX_CREOLE), "No link rendering invalid"); end Test_Wiki_Link; -- ------------------------------ -- Test quote rendering. -- ------------------------------ procedure Test_Wiki_Quote (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>", Writers.To_Html ("{{quote}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>", Writers.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"" cite=""http://www.sun.com"">quote</q></p>", Writers.To_Html ("{{quote|en|http://www.sun.com}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p>{quote}}</p>", Writers.To_Html ("{quote}}", SYNTAX_DOTCLEAR), "No quote rendering invalid"); end Test_Wiki_Quote; -- ------------------------------ -- Test line break rendering. -- ------------------------------ procedure Test_Wiki_Line_Break (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p>a<br></br>b</p>", Writers.To_Html ("a%%%b", SYNTAX_DOTCLEAR), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a<br></br>b</p>", Writers.To_Html ("a\\b", SYNTAX_CREOLE), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%%b</p>", Writers.To_Html ("a%%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%b</p>", Writers.To_Html ("a%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); end Test_Wiki_Line_Break; -- ------------------------------ -- Test image rendering. -- ------------------------------ procedure Test_Wiki_Image (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png""></img></p>", Writers.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png""></img></p>", Writers.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" longdesc=""describe"" " & "src=""/image/t.png""></img></p>", Writers.To_Html ("((/image/t.png|title|D|describe))", SYNTAX_DOTCLEAR), "Image rendering invalid"); end Test_Wiki_Image; -- ------------------------------ -- Test preformatted rendering. -- ------------------------------ procedure Test_Wiki_Preformatted (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>", Writers.To_Html ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>", Writers.To_Html ("///" & LF & "* code *" & LF & "///", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); end Test_Wiki_Preformatted; -- ------------------------------ -- Test the text renderer. -- ------------------------------ procedure Test_Wiki_Text_Renderer (T : in out Test) is begin Util.Tests.Assert_Equals (T, ASCII.LF & "code", Writers.To_Text ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF, Writers.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE), "Preformat rendering invalid"); end Test_Wiki_Text_Renderer; end AWA.Wikis.Parsers.Tests;
----------------------------------------------------------------------- -- awa-wikis-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with AWA.Wikis.Writers; package body AWA.Wikis.Parsers.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Parsers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (bold)", Test_Wiki_Bold'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (italic)", Test_Wiki_Italic'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (italic, bold)", Test_Wiki_Formats'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (headings)", Test_Wiki_Section'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (lists)", Test_Wiki_List'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (links)", Test_Wiki_Link'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (quote)", Test_Wiki_Quote'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (line break)", Test_Wiki_Line_Break'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (image)", Test_Wiki_Image'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (preformatted)", Test_Wiki_Preformatted'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Text.Renderer", Test_Wiki_Text_Renderer'Access); end Add_Tests; -- ------------------------------ -- Test bold rendering. -- ------------------------------ procedure Test_Wiki_Bold (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>", Writers.To_Html ("*bold*", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Writers.To_Html ("x *bold* y", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>", Writers.To_Html ("x *bold y", SYNTAX_MIX), "Bold rendering invalid (MIX)"); Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>", Writers.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>", Writers.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR), "No bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Writers.To_Html ("x '''bold''' y", SYNTAX_PHPBB), "Bold rendering invalid (PHPBB)"); end Test_Wiki_Bold; -- ------------------------------ -- Test italic rendering. -- ------------------------------ procedure Test_Wiki_Italic (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>item</i></p>", Writers.To_Html ("_item_", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Writers.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Writers.To_Html ("x _item y", SYNTAX_MIX), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Writers.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Writers.To_Html ("x ''item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>", Writers.To_Html ("x 'item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); end Test_Wiki_Italic; -- ------------------------------ -- Test various format rendering. -- ------------------------------ procedure Test_Wiki_Formats (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>", Writers.To_Html ("_it*bold*em_", SYNTAX_GOOGLE), "Italic+Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Writers.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Writers.To_Html ("x _item y", SYNTAX_GOOGLE), "Italic rendering invalid"); end Test_Wiki_Formats; -- ------------------------------ -- Test heading rendering. -- ------------------------------ procedure Test_Wiki_Section (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<h1>item</h1>", Writers.To_Html ("= item =", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h2>item</h2>", Writers.To_Html ("== item == ", SYNTAX_GOOGLE), "H2 rendering invalid"); Util.Tests.Assert_Equals (T, "<h3>item</h3>", Writers.To_Html ("=== item === ", SYNTAX_GOOGLE), "H3 rendering invalid"); Util.Tests.Assert_Equals (T, "<h4>item</h4>", Writers.To_Html ("==== item ==== ", SYNTAX_GOOGLE), "H4 rendering invalid"); Util.Tests.Assert_Equals (T, "<h5>item</h5>", Writers.To_Html ("===== item =====", SYNTAX_GOOGLE), "H5 rendering invalid"); Util.Tests.Assert_Equals (T, "<h6>item</h6>", Writers.To_Html ("====== item ===", SYNTAX_GOOGLE), "H6 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>", Writers.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>", Writers.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =", SYNTAX_GOOGLE), "H1 rendering invalid"); end Test_Wiki_Section; -- ------------------------------ -- Test list rendering. -- ------------------------------ procedure Test_Wiki_List (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>", Writers.To_Html ("# item", SYNTAX_GOOGLE), "Ordered list rendering invalid"); Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF & "</li><li>item2 item2" & ASCII.LF & "</li><li><ol>item3</li></ol></ol>", Writers.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3", SYNTAX_GOOGLE), "Ordered rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Writers.To_Html (" * item", SYNTAX_GOOGLE), "Bullet list rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Writers.To_Html ("* item", SYNTAX_DOTCLEAR), "Bullet list rendering invalid"); end Test_Wiki_List; -- ------------------------------ -- Test link rendering. -- ------------------------------ procedure Test_Wiki_Link (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>", Writers.To_Html ("[name]", SYNTAX_GOOGLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a title=""some"" lang=""en"" " & "href=""http://www.joe.com/item"">name </a></p>", Writers.To_Html ("[name |http://www.joe.com/item|en|some]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>", Writers.To_Html ("[[name]]", SYNTAX_CREOLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p>[d</p>", Writers.To_Html ("[d", SYNTAX_CREOLE), "No link rendering invalid"); end Test_Wiki_Link; -- ------------------------------ -- Test quote rendering. -- ------------------------------ procedure Test_Wiki_Quote (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>", Writers.To_Html ("{{quote}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>", Writers.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"" cite=""http://www.sun.com"">quote</q></p>", Writers.To_Html ("{{quote|en|http://www.sun.com}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p>{quote}}</p>", Writers.To_Html ("{quote}}", SYNTAX_DOTCLEAR), "No quote rendering invalid"); end Test_Wiki_Quote; -- ------------------------------ -- Test line break rendering. -- ------------------------------ procedure Test_Wiki_Line_Break (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Writers.To_Html ("a%%%b", SYNTAX_DOTCLEAR), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Writers.To_Html ("a\\b", SYNTAX_CREOLE), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%%b</p>", Writers.To_Html ("a%%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%b</p>", Writers.To_Html ("a%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); end Test_Wiki_Line_Break; -- ------------------------------ -- Test image rendering. -- ------------------------------ procedure Test_Wiki_Image (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png""></img></p>", Writers.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png""></img></p>", Writers.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" longdesc=""describe"" " & "src=""/image/t.png""></img></p>", Writers.To_Html ("((/image/t.png|title|D|describe))", SYNTAX_DOTCLEAR), "Image rendering invalid"); end Test_Wiki_Image; -- ------------------------------ -- Test preformatted rendering. -- ------------------------------ procedure Test_Wiki_Preformatted (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>", Writers.To_Html ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>", Writers.To_Html ("///" & LF & "* code *" & LF & "///", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); end Test_Wiki_Preformatted; -- ------------------------------ -- Test the text renderer. -- ------------------------------ procedure Test_Wiki_Text_Renderer (T : in out Test) is begin Util.Tests.Assert_Equals (T, ASCII.LF & "code", Writers.To_Text ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF, Writers.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE), "Preformat rendering invalid"); end Test_Wiki_Text_Renderer; end AWA.Wikis.Parsers.Tests;
Update the test after fix in the wiki break generation
Update the test after fix in the wiki break generation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8bbe2443268eb02172744e5f1ea73b00ae41f32f
samples/userdb.adb
samples/userdb.adb
----------------------------------------------------------------------- -- userdb -- Example to find/create an object from the database -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with ADO.Drivers; with ADO.Sessions; with ADO.SQL; with ADO.Sessions.Factory; with Samples.User.Model; with Ada.Text_IO; with Ada.Strings.Unbounded; with ADO.Statements; with ADO.Queries; with Util.Log.Loggers; with GNAT.Command_Line; procedure Userdb is use ADO; use Ada; use Ada.Strings.Unbounded; use Samples.User.Model; use ADO.Statements; use GNAT.Command_Line; Factory : ADO.Sessions.Factory.Session_Factory; User : User_Ref; Users : User_Vector; procedure List_Users (Filter : in String); procedure List_User_Info; procedure Initialize (File : in String); -- ------------------------------ -- List users -- ------------------------------ procedure List_Users (Filter : in String) is use User_Vectors; DB : ADO.Sessions.Session := Factory.Get_Session; Statement : ADO.Statements.Query_Statement := DB.Create_Statement (Filter); Query : ADO.SQL.Query; begin List (Object => Users, Session => DB, Query => Query); if Users.Is_Empty then Text_IO.Put_Line ("List is empty"); else declare Iter : User_Vectors.Cursor := First (Users); begin while Has_Element (Iter) loop User := Element (Iter); Text_IO.Put_Line (Identifier'Image (User.Get_Id) & " " & To_String (User.Get_Name) & " " & To_String (User.Get_Email)); User_Vectors.Next (Iter); end loop; end; end if; Statement := DB.Create_Statement ("select count(*) from user"); Statement.Execute; if not Statement.Has_Elements then Text_IO.Put_Line ("Count query failed..."); end if; declare Count : constant Integer := Statement.Get_Integer (0); begin Text_IO.Put_Line ("Count: " & Integer'Image (Count)); end; end List_Users; -- ------------------------------ -- List users -- ------------------------------ procedure List_User_Info is use Samples.User.Model.User_Info_Vectors; DB : ADO.Sessions.Session := Factory.Get_Session; Users : Samples.User.Model.User_Info_Vector; Context : ADO.Queries.Context; begin Context.Set_Query (Samples.User.Model.Query_User_List); List (Object => Users, Session => DB, Context => Context); if Users.Is_Empty then Text_IO.Put_Line ("User info list is empty"); else declare Iter : Cursor := First (Users); User : Samples.User.Model.User_Info; begin while Has_Element (Iter) loop User := Element (Iter); Text_IO.Put_Line (Identifier'Image (User.Id) & " " & To_String (User.Name) & " " & To_String (User.Email)); Next (Iter); end loop; end; end if; end List_User_Info; procedure Initialize (File : in String) is begin Util.Log.Loggers.Initialize (File); ADO.Drivers.Initialize (File); end Initialize; begin Initialize ("samples.properties"); Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session; Query : ADO.SQL.Query; Found : Boolean; begin DB.Begin_Transaction; List_User_Info; List_Users (Filter => ""); loop declare Name : constant String := Get_Argument; begin exit when Name = ""; Query.Bind_Param (1, Name); Query.Set_Filter ("name = ?"); User.Find (Session => DB, Query => Query, Found => Found); if User.Is_Null or not Found then User.Set_Name (Name); User.Set_Email (Name & "@gmail.com"); User.Set_Description ("My friend " & Name); -- User.Set_Password ("my password"); User.Set_Status (0); User.Save (DB); Text_IO.Put_Line ("User created: " & Identifier'Image (User.Get_Id)); else Text_IO.Put_Line ("User " & Name & ": " & Identifier'Image (User.Get_Id)); end if; end; end loop; DB.Rollback; exception when ADO.Sessions.NOT_FOUND => Text_IO.Put_Line ("User 23 does not exist"); end; Text_IO.Put_Line ("Exiting"); end Userdb;
----------------------------------------------------------------------- -- userdb -- Example to find/create an object from the database -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with ADO.Drivers.Initializer; with ADO.Sessions; with ADO.SQL; with ADO.Sessions.Factory; with Samples.User.Model; with Ada.Text_IO; with Ada.Strings.Unbounded; with ADO.Statements; with ADO.Queries; with Util.Log.Loggers; with GNAT.Command_Line; procedure Userdb is use ADO; use Ada; use Ada.Strings.Unbounded; use Samples.User.Model; use ADO.Statements; use GNAT.Command_Line; Factory : ADO.Sessions.Factory.Session_Factory; User : User_Ref; Users : User_Vector; procedure List_Users (Filter : in String); procedure List_User_Info; procedure Initialize (File : in String); -- ------------------------------ -- List users -- ------------------------------ procedure List_Users (Filter : in String) is use User_Vectors; DB : ADO.Sessions.Session := Factory.Get_Session; Statement : ADO.Statements.Query_Statement := DB.Create_Statement (Filter); Query : ADO.SQL.Query; begin List (Object => Users, Session => DB, Query => Query); if Users.Is_Empty then Text_IO.Put_Line ("List is empty"); else declare Iter : User_Vectors.Cursor := First (Users); begin while Has_Element (Iter) loop User := Element (Iter); Text_IO.Put_Line (Identifier'Image (User.Get_Id) & " " & To_String (User.Get_Name) & " " & To_String (User.Get_Email)); User_Vectors.Next (Iter); end loop; end; end if; Statement := DB.Create_Statement ("select count(*) from user"); Statement.Execute; if not Statement.Has_Elements then Text_IO.Put_Line ("Count query failed..."); end if; declare Count : constant Integer := Statement.Get_Integer (0); begin Text_IO.Put_Line ("Count: " & Integer'Image (Count)); end; end List_Users; -- ------------------------------ -- List users -- ------------------------------ procedure List_User_Info is use Samples.User.Model.User_Info_Vectors; DB : ADO.Sessions.Session := Factory.Get_Session; Users : Samples.User.Model.User_Info_Vector; Context : ADO.Queries.Context; begin Context.Set_Query (Samples.User.Model.Query_User_List); List (Object => Users, Session => DB, Context => Context); if Users.Is_Empty then Text_IO.Put_Line ("User info list is empty"); else declare Iter : Cursor := First (Users); User : Samples.User.Model.User_Info; begin while Has_Element (Iter) loop User := Element (Iter); Text_IO.Put_Line (Identifier'Image (User.Id) & " " & To_String (User.Name) & " " & To_String (User.Email)); Next (Iter); end loop; end; end if; end List_User_Info; procedure Initialize (File : in String) is procedure Init is new ADO.Drivers.Initializer (String, ADO.Drivers.Initialize); begin Util.Log.Loggers.Initialize (File); Init (File); end Initialize; begin Initialize ("samples.properties"); Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session; Query : ADO.SQL.Query; Found : Boolean; begin DB.Begin_Transaction; List_User_Info; List_Users (Filter => ""); loop declare Name : constant String := Get_Argument; begin exit when Name = ""; Query.Bind_Param (1, Name); Query.Set_Filter ("name = ?"); User.Find (Session => DB, Query => Query, Found => Found); if User.Is_Null or not Found then User.Set_Name (Name); User.Set_Email (Name & "@gmail.com"); User.Set_Description ("My friend " & Name); -- User.Set_Password ("my password"); User.Set_Status (0); User.Save (DB); Text_IO.Put_Line ("User created: " & Identifier'Image (User.Get_Id)); else Text_IO.Put_Line ("User " & Name & ": " & Identifier'Image (User.Get_Id)); end if; end; end loop; DB.Rollback; exception when ADO.Sessions.NOT_FOUND => Text_IO.Put_Line ("User 23 does not exist"); end; Text_IO.Put_Line ("Exiting"); end Userdb;
Update the driver initialization
Update the driver initialization
Ada
apache-2.0
stcarrez/ada-ado
f7b62e8fa8af8dc1898c56937ff421a4882f54f9
src/sys/streams/util-streams-buffered.ads
src/sys/streams/util-streams-buffered.ads
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010, 2013, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Finalization; -- == Buffered Streams == -- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output -- and input stream respectively which manages an output or input buffer. The data is -- first written to the buffer and when the buffer is full or flushed, it gets written -- to the target output stream. -- -- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well -- as the target output stream onto which the data will be flushed. For example, a -- pipe stream could be created and configured to use the buffer as follows: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Output_Buffer_Stream; -- ... -- Buffer.Initialize (Output => Pipe'Access, -- Size => 1024); -- -- In this example, the buffer of 1024 bytes is configured to flush its content to the -- pipe input stream so that what is written to the buffer will be received as input by -- the program. -- The `Output_Buffer_Stream` provides write operation that deal only with binary data -- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from -- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides -- several operations to write character and strings. -- -- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size -- and either an input stream or an input content. When configured, the input stream is used -- to fill the input stream buffer. The buffer configuration is very similar as the -- output stream: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Access, Size => 1024); -- -- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus -- getting the program's output. package Util.Streams.Buffered is -- pragma Preelaborate; type Buffer_Access is access Ada.Streams.Stream_Element_Array; -- ----------------------- -- Buffer stream -- ----------------------- -- The `Buffer_Stream` is the base type for the `Output_Buffer_Stream` -- and `Input_Buffer_Stream` types. It holds the buffer and read/write positions. type Buffer_Stream is limited new Ada.Finalization.Limited_Controlled with private; -- Initialize the stream to read or write on the buffer. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Buffer_Stream; Size : in Positive); -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Buffer_Stream; Content : in String); -- Get the direct access to the buffer. function Get_Buffer (Stream : in Buffer_Stream) return Buffer_Access; -- Get the number of element in the stream. function Get_Size (Stream : in Buffer_Stream) return Natural; -- Release the buffer. overriding procedure Finalize (Object : in out Buffer_Stream); -- ----------------------- -- Output buffer stream -- ----------------------- -- The `Output_Buffer_Stream` is an output stream which uses -- an intermediate buffer to write the data. -- -- It is necessary to call `Flush` to make sure the data -- is written to the target stream. The `Flush` operation will -- be called when finalizing the output buffer stream. type Output_Buffer_Stream is limited new Buffer_Stream and Output_Stream with private; -- Initialize the stream to write on the given streams. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Output_Buffer_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Output_Buffer_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Output_Buffer_Stream); -- Flush the buffer in the `Into` array and return the index of the -- last element (inclusive) in `Last`. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Flush the buffer stream to the unbounded string. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String); -- Flush the stream and release the buffer. overriding procedure Finalize (Stream : in out Output_Buffer_Stream); type Input_Buffer_Stream is limited new Buffer_Stream and Input_Stream with private; -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String); -- Initialize the stream to read the given streams. procedure Initialize (Stream : in out Input_Buffer_Stream; Input : access Input_Stream'Class; Size : in Positive); -- Initialize the stream from the buffer created for an output stream. procedure Initialize (Stream : in out Input_Buffer_Stream; From : in out Buffer_Stream'Class); -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Input_Buffer_Stream); -- Read one character from the input stream. procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character); procedure Read (Stream : in out Input_Buffer_Stream; Value : out Ada.Streams.Stream_Element); procedure Read (Stream : in out Input_Buffer_Stream; Char : out Wide_Wide_Character); -- Read into the buffer as many bytes as possible and return in -- `last` the position of the last byte read. overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String); procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Returns True if the end of the stream is reached. function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean; type Input_Output_Buffer_Stream is abstract limited new Buffer_Stream and Input_Stream and Output_Stream with private; private use Ada.Streams; type Buffer_Stream is limited new Ada.Finalization.Limited_Controlled with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; end record; type Output_Buffer_Stream is limited new Buffer_Stream and Output_Stream with record -- The output stream to use for flushing the buffer. Output : access Output_Stream'Class; No_Flush : Boolean := False; end record; type Input_Buffer_Stream is limited new Buffer_Stream and Input_Stream with record -- The input stream to use to fill the buffer. Input : access Input_Stream'Class; -- Reached end of file when reading. Eof : Boolean := False; end record; type Input_Output_Buffer_Stream is abstract limited new Buffer_Stream and Input_Stream and Output_Stream with record -- The output stream to use for flushing the buffer. Output : access Output_Stream'Class; No_Flush : Boolean := False; -- The input stream to use to fill the buffer. Input : access Input_Stream'Class; -- Reached end of file when reading. Eof : Boolean := False; end record; end Util.Streams.Buffered;
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Finalization; -- == Buffered Streams == -- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output -- and input stream respectively which manages an output or input buffer. The data is -- first written to the buffer and when the buffer is full or flushed, it gets written -- to the target output stream. -- -- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well -- as the target output stream onto which the data will be flushed. For example, a -- pipe stream could be created and configured to use the buffer as follows: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Output_Buffer_Stream; -- ... -- Buffer.Initialize (Output => Pipe'Unchecked_Access, -- Size => 1024); -- -- In this example, the buffer of 1024 bytes is configured to flush its content to the -- pipe input stream so that what is written to the buffer will be received as input by -- the program. -- The `Output_Buffer_Stream` provides write operation that deal only with binary data -- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from -- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides -- several operations to write character and strings. -- -- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size -- and either an input stream or an input content. When configured, the input stream is used -- to fill the input stream buffer. The buffer configuration is very similar as the -- output stream: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024); -- -- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus -- getting the program's output. package Util.Streams.Buffered is pragma Preelaborate; type Buffer_Access is access Ada.Streams.Stream_Element_Array; -- ----------------------- -- Buffer stream -- ----------------------- -- The `Buffer_Stream` is the base type for the `Output_Buffer_Stream` -- and `Input_Buffer_Stream` types. It holds the buffer and read/write positions. type Buffer_Stream is limited new Ada.Finalization.Limited_Controlled with private; -- Initialize the stream to read or write on the buffer. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Buffer_Stream; Size : in Positive); -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Buffer_Stream; Content : in String); -- Get the direct access to the buffer. function Get_Buffer (Stream : in Buffer_Stream) return Buffer_Access; -- Get the number of element in the stream. function Get_Size (Stream : in Buffer_Stream) return Natural; -- Release the buffer. overriding procedure Finalize (Object : in out Buffer_Stream); -- ----------------------- -- Output buffer stream -- ----------------------- -- The `Output_Buffer_Stream` is an output stream which uses -- an intermediate buffer to write the data. -- -- It is necessary to call `Flush` to make sure the data -- is written to the target stream. The `Flush` operation will -- be called when finalizing the output buffer stream. type Output_Buffer_Stream is limited new Buffer_Stream and Output_Stream with private; -- Initialize the stream to write on the given streams. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Output_Buffer_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Output_Buffer_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Output_Buffer_Stream); -- Flush the buffer in the `Into` array and return the index of the -- last element (inclusive) in `Last`. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Flush the buffer stream to the unbounded string. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String); -- Flush the stream and release the buffer. overriding procedure Finalize (Stream : in out Output_Buffer_Stream); type Input_Buffer_Stream is limited new Buffer_Stream and Input_Stream with private; -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String); -- Initialize the stream to read the given streams. procedure Initialize (Stream : in out Input_Buffer_Stream; Input : access Input_Stream'Class; Size : in Positive); -- Initialize the stream from the buffer created for an output stream. procedure Initialize (Stream : in out Input_Buffer_Stream; From : in out Buffer_Stream'Class); -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Input_Buffer_Stream); -- Read one character from the input stream. procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character); procedure Read (Stream : in out Input_Buffer_Stream; Value : out Ada.Streams.Stream_Element); procedure Read (Stream : in out Input_Buffer_Stream; Char : out Wide_Wide_Character); -- Read into the buffer as many bytes as possible and return in -- `last` the position of the last byte read. overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String); procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Returns True if the end of the stream is reached. function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean; type Input_Output_Buffer_Stream is abstract limited new Buffer_Stream and Input_Stream and Output_Stream with private; private use Ada.Streams; type Buffer_Stream is limited new Ada.Finalization.Limited_Controlled with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; end record; type Output_Buffer_Stream is limited new Buffer_Stream and Output_Stream with record -- The output stream to use for flushing the buffer. Output : access Output_Stream'Class; No_Flush : Boolean := False; end record; type Input_Buffer_Stream is limited new Buffer_Stream and Input_Stream with record -- The input stream to use to fill the buffer. Input : access Input_Stream'Class; -- Reached end of file when reading. Eof : Boolean := False; end record; type Input_Output_Buffer_Stream is abstract limited new Buffer_Stream and Input_Stream and Output_Stream with record -- The output stream to use for flushing the buffer. Output : access Output_Stream'Class; No_Flush : Boolean := False; -- The input stream to use to fill the buffer. Input : access Input_Stream'Class; -- Reached end of file when reading. Eof : Boolean := False; end record; end Util.Streams.Buffered;
Fix documentation example
Fix documentation example
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c07c2943a8968c0d541f0a8775fed891b301e79a
src/imago-il.ads
src/imago-il.ads
pragma License (Modified_GPL); ------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: Modified GNU GPLv3 or any later as published by Free Software -- -- Foundation (GMGPL). -- -- -- -- Copyright © 2014 darkestkhan -- ------------------------------------------------------------------------------ -- This Program is Free Software: You can redistribute it and/or modify -- -- it under the terms of The GNU General Public License as published by -- -- the Free Software Foundation: either version 3 of the license, or -- -- (at your option) any later version. -- -- -- -- This Program is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- -- GNU General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public License -- -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- ------------------------------------------------------------------------------ with System; with Imago.Binary; use Imago; package Imago.IL is -------------------------------------------------------------------------- --------------- -- T Y P E S -- --------------- -------------------------------------------------------------------------- -- New names for old types. subtype Bitfield is Binary.Word; subtype Bool is Binary.Byte; subtype Byte is Binary.S_Byte; subtype ClampD is Long_Float range 0.0 .. 1.0; subtype ClampF is Float range 0.0 .. 1.0; subtype ClampH is Short_Float range 0.0 .. 1.0; subtype Double is Long_Float; subtype Int is Integer; subtype Short is Short_Integer; subtype SizeI is Integer; subtype UByte is Binary.Byte; subtype UShort is Binary.Short; subtype UInt is Binary.Word; subtype Pointer is System.Address; -------------------------------------------------------------------------- -- Try to bring some touch of order to the ILenum mess. subtype Enum is Binary.Word; -------------------------------------------------------------------------- ----------------------- -- C O N S T A N T S -- ----------------------- -------------------------------------------------------------------------- -- Useful values. Null_Pointer: constant Pointer := System.Null_Address; -------------------------------------------------------------------------- -- "Enumeration" constants. IL_FALSE : constant Bool := 16#0#; IL_TRUE : constant Bool := 16#1#; -- Data formats. IL_COLOUR_INDEX : constant Enum := 16#1900#; IL_COLOR_INDEX : constant Enum := 16#1900#; IL_ALPHA : constant Enum := 16#1906#; IL_RGB : constant Enum := 16#1907#; IL_RGBA : constant Enum := 16#1908#; IL_BGR : constant Enum := 16#80E0#; IL_BGRA : constant Enum := 16#80E1#; IL_LUMINANCE : constant Enum := 16#1909#; IL_LUMINANCE_ALPHA : constant Enum := 16#190A#; -- Types of data. IL_BYTE : constant Enum := 16#1400#; IL_UNSIGNED_BYTE : constant Enum := 16#1401#; IL_SHORT : constant Enum := 16#1402#; IL_UNSIGNED_SHORT : constant Enum := 16#1403#; IL_INT : constant Enum := 16#1404#; IL_UNSIGNED_INT : constant Enum := 16#1405#; IL_FLOAT : constant Enum := 16#1406#; IL_DOUBLE : constant Enum := 16#140A#; IL_HALF : constant Enum := 16#140B#; -- IL specific defines. IL_VENDOR : constant Enum := 16#1F00#; IL_LOAD_EXT : constant Enum := 16#1F01#; IL_SAVE_EXT : constant Enum := 16#1F02#; IL_VERSION_1_7_8 : constant Enum := 16#1#; IL_VERSION : constant Enum := 178; -- Attribute bits. IL_ORIGIN_BIT : constant Bitfield := 16#0000_0001#; IL_FILE_BIT : constant Bitfield := 16#0000_0002#; IL_PAL_BIT : constant Bitfield := 16#0000_0004#; IL_FORMAT_BIT : constant Bitfield := 16#0000_0008#; IL_TYPE_BIT : constant Bitfield := 16#0000_0010#; IL_COMPRESS_BIT : constant Bitfield := 16#0000_0020#; IL_LOADFAIL_BIT : constant Bitfield := 16#0000_0040#; IL_FORMAT_SPECIFIC_BIT : constant Bitfield := 16#0000_0080#; IL_ALL_ATTRIB_BITS : constant Bitfield := 16#000F_FFFF#; -- Types of palettes. IL_PAL_NONE : constant Enum := 16#0400#; IL_PAL_RGB24 : constant Enum := 16#0401#; IL_PAL_RGB32 : constant Enum := 16#0402#; IL_PAL_RGBA32 : constant Enum := 16#0403#; IL_PAL_BGR24 : constant Enum := 16#0404#; IL_PAL_BGR32 : constant Enum := 16#0405#; IL_PAL_BGRA32 : constant Enum := 16#0406#; -- Types of images. IL_TYPE_UNKNOWN : constant Enum := 16#0000#; IL_BMP : constant Enum := 16#0420#; IL_CUT : constant Enum := 16#0421#; IL_DOOM : constant Enum := 16#0422#; IL_DOOM_FLAT : constant Enum := 16#0423#; IL_ICO : constant Enum := 16#0424#; IL_JPG : constant Enum := 16#0425#; IL_JFIF : constant Enum := 16#0425#; IL_ILBM : constant Enum := 16#0426#; IL_PCD : constant Enum := 16#0427#; IL_PCX : constant Enum := 16#0428#; IL_PIC : constant Enum := 16#0429#; IL_PNG : constant Enum := 16#042A#; IL_PNM : constant Enum := 16#042B#; IL_SGI : constant Enum := 16#042C#; IL_TGA : constant Enum := 16#042D#; IL_TIF : constant Enum := 16#042E#; IL_CHEAD : constant Enum := 16#042F#; IL_RAW : constant Enum := 16#0430#; IL_MDL : constant Enum := 16#0431#; IL_WAL : constant Enum := 16#0432#; IL_LIF : constant Enum := 16#0434#; IL_MNG : constant Enum := 16#0435#; IL_JNG : constant Enum := 16#0435#; IL_GIF : constant Enum := 16#0436#; IL_DDS : constant Enum := 16#0437#; IL_DCX : constant Enum := 16#0438#; IL_PSD : constant Enum := 16#0439#; IL_EXIF : constant Enum := 16#043A#; IL_PSP : constant Enum := 16#043B#; IL_PIX : constant Enum := 16#043C#; IL_PXR : constant Enum := 16#043D#; IL_XPM : constant Enum := 16#043E#; IL_HDR : constant Enum := 16#043F#; IL_ICNS : constant Enum := 16#0440#; IL_JP2 : constant Enum := 16#0441#; IL_EXR : constant Enum := 16#0442#; IL_WDP : constant Enum := 16#0443#; IL_VTF : constant Enum := 16#0444#; IL_WBMP : constant Enum := 16#0445#; IL_SUN : constant Enum := 16#0446#; IL_IFF : constant Enum := 16#0447#; IL_TPL : constant Enum := 16#0448#; IL_FITS : constant Enum := 16#0449#; IL_DICOM : constant Enum := 16#044A#; IL_IWI : constant Enum := 16#044B#; IL_BLP : constant Enum := 16#044C#; IL_FTX : constant Enum := 16#044D#; IL_ROT : constant Enum := 16#044E#; IL_TEXTURE : constant Enum := 16#044F#; IL_DPX : constant Enum := 16#0450#; IL_UTX : constant Enum := 16#0451#; IL_MP3 : constant Enum := 16#0452#; IL_JASC_PAL : constant Enum := 16#0475#; -- Types of errors. IL_NO_ERROR : constant Enum := 16#0000#; IL_INVALID_ENUM : constant Enum := 16#0501#; IL_OUT_OF_MEMORY : constant Enum := 16#0502#; IL_FORMAT_NOT_SUPPORTED : constant Enum := 16#0503#; IL_INTERNAL_ERROR : constant Enum := 16#0504#; IL_INVALID_VALUE : constant Enum := 16#0505#; IL_ILLEGAL_OPERATION : constant Enum := 16#0506#; IL_ILLEGAL_FILE_VALUE : constant Enum := 16#0507#; IL_INVALID_FILE_HEADER : constant Enum := 16#0508#; IL_INVALID_PARAM : constant Enum := 16#0509#; IL_COULD_NOT_OPEN_FILE : constant Enum := 16#050A#; IL_INVALID_EXTENSION : constant Enum := 16#050B#; IL_FILE_ALREADY_EXISTS : constant Enum := 16#050C#; IL_OUT_FORMAT_SAME : constant Enum := 16#050D#; IL_STACK_OVERFLOW : constant Enum := 16#050E#; IL_STACK_UNDERFLOW : constant Enum := 16#050F#; IL_INVALID_CONVERSION : constant Enum := 16#0510#; IL_BAD_DIMENSIONS : constant Enum := 16#0511#; IL_FILE_READ_ERROR : constant Enum := 16#0512#; IL_FILE_WRITE_ERROR : constant Enum := 16#0513#; IL_LIB_GIF_ERROR : constant Enum := 16#05E1#; IL_LIB_JPEG_ERROR : constant Enum := 16#05E2#; IL_LIB_PNG_ERROR : constant Enum := 16#05E3#; IL_LIB_TIFF_ERROR : constant Enum := 16#05E4#; IL_LIB_MNG_ERROR : constant Enum := 16#05E5#; IL_LIB_JP2_ERROR : constant Enum := 16#05E6#; IL_LIB_EXR_ERROR : constant Enum := 16#05E7#; IL_UNKNOWN_ERROR : constant Enum := 16#05FF#; -------------------------------------------------------------------------- end Imago.IL;
pragma License (Modified_GPL); ------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: Modified GNU GPLv3 or any later as published by Free Software -- -- Foundation (GMGPL). -- -- -- -- Copyright © 2014 darkestkhan -- ------------------------------------------------------------------------------ -- This Program is Free Software: You can redistribute it and/or modify -- -- it under the terms of The GNU General Public License as published by -- -- the Free Software Foundation: either version 3 of the license, or -- -- (at your option) any later version. -- -- -- -- This Program is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- -- GNU General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public License -- -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- ------------------------------------------------------------------------------ with System; with Imago.Binary; use Imago; package Imago.IL is -------------------------------------------------------------------------- --------------- -- T Y P E S -- --------------- -------------------------------------------------------------------------- -- New names for old types. subtype Bitfield is Binary.Word; subtype Bool is Binary.Byte; subtype Byte is Binary.S_Byte; subtype ClampD is Long_Float range 0.0 .. 1.0; subtype ClampF is Float range 0.0 .. 1.0; subtype ClampH is Short_Float range 0.0 .. 1.0; subtype Double is Long_Float; subtype Int is Integer; subtype Short is Short_Integer; subtype SizeI is Integer; subtype UByte is Binary.Byte; subtype UShort is Binary.Short; subtype UInt is Binary.Word; subtype Pointer is System.Address; -------------------------------------------------------------------------- -- Try to bring some touch of order to the ILenum mess. subtype Enum is Binary.Word; -------------------------------------------------------------------------- ----------------------- -- C O N S T A N T S -- ----------------------- -------------------------------------------------------------------------- -- Useful values. Null_Pointer: constant Pointer := System.Null_Address; -------------------------------------------------------------------------- -- "Enumeration" constants. IL_FALSE : constant Bool := 16#0#; IL_TRUE : constant Bool := 16#1#; -- Data formats. IL_COLOUR_INDEX : constant Enum := 16#1900#; IL_COLOR_INDEX : constant Enum := 16#1900#; IL_ALPHA : constant Enum := 16#1906#; IL_RGB : constant Enum := 16#1907#; IL_RGBA : constant Enum := 16#1908#; IL_BGR : constant Enum := 16#80E0#; IL_BGRA : constant Enum := 16#80E1#; IL_LUMINANCE : constant Enum := 16#1909#; IL_LUMINANCE_ALPHA : constant Enum := 16#190A#; -- Types of data. IL_BYTE : constant Enum := 16#1400#; IL_UNSIGNED_BYTE : constant Enum := 16#1401#; IL_SHORT : constant Enum := 16#1402#; IL_UNSIGNED_SHORT : constant Enum := 16#1403#; IL_INT : constant Enum := 16#1404#; IL_UNSIGNED_INT : constant Enum := 16#1405#; IL_FLOAT : constant Enum := 16#1406#; IL_DOUBLE : constant Enum := 16#140A#; IL_HALF : constant Enum := 16#140B#; -- IL specific defines. IL_VENDOR : constant Enum := 16#1F00#; IL_LOAD_EXT : constant Enum := 16#1F01#; IL_SAVE_EXT : constant Enum := 16#1F02#; IL_VERSION_1_7_8 : constant Enum := 16#1#; IL_VERSION : constant Enum := 178; -- Attribute bits. IL_ORIGIN_BIT : constant Bitfield := 16#0000_0001#; IL_FILE_BIT : constant Bitfield := 16#0000_0002#; IL_PAL_BIT : constant Bitfield := 16#0000_0004#; IL_FORMAT_BIT : constant Bitfield := 16#0000_0008#; IL_TYPE_BIT : constant Bitfield := 16#0000_0010#; IL_COMPRESS_BIT : constant Bitfield := 16#0000_0020#; IL_LOADFAIL_BIT : constant Bitfield := 16#0000_0040#; IL_FORMAT_SPECIFIC_BIT : constant Bitfield := 16#0000_0080#; IL_ALL_ATTRIB_BITS : constant Bitfield := 16#000F_FFFF#; -- Types of palettes. IL_PAL_NONE : constant Enum := 16#0400#; IL_PAL_RGB24 : constant Enum := 16#0401#; IL_PAL_RGB32 : constant Enum := 16#0402#; IL_PAL_RGBA32 : constant Enum := 16#0403#; IL_PAL_BGR24 : constant Enum := 16#0404#; IL_PAL_BGR32 : constant Enum := 16#0405#; IL_PAL_BGRA32 : constant Enum := 16#0406#; -- Types of images. IL_TYPE_UNKNOWN : constant Enum := 16#0000#; IL_BMP : constant Enum := 16#0420#; IL_CUT : constant Enum := 16#0421#; IL_DOOM : constant Enum := 16#0422#; IL_DOOM_FLAT : constant Enum := 16#0423#; IL_ICO : constant Enum := 16#0424#; IL_JPG : constant Enum := 16#0425#; IL_JFIF : constant Enum := 16#0425#; IL_ILBM : constant Enum := 16#0426#; IL_PCD : constant Enum := 16#0427#; IL_PCX : constant Enum := 16#0428#; IL_PIC : constant Enum := 16#0429#; IL_PNG : constant Enum := 16#042A#; IL_PNM : constant Enum := 16#042B#; IL_SGI : constant Enum := 16#042C#; IL_TGA : constant Enum := 16#042D#; IL_TIF : constant Enum := 16#042E#; IL_CHEAD : constant Enum := 16#042F#; IL_RAW : constant Enum := 16#0430#; IL_MDL : constant Enum := 16#0431#; IL_WAL : constant Enum := 16#0432#; IL_LIF : constant Enum := 16#0434#; IL_MNG : constant Enum := 16#0435#; IL_JNG : constant Enum := 16#0435#; IL_GIF : constant Enum := 16#0436#; IL_DDS : constant Enum := 16#0437#; IL_DCX : constant Enum := 16#0438#; IL_PSD : constant Enum := 16#0439#; IL_EXIF : constant Enum := 16#043A#; IL_PSP : constant Enum := 16#043B#; IL_PIX : constant Enum := 16#043C#; IL_PXR : constant Enum := 16#043D#; IL_XPM : constant Enum := 16#043E#; IL_HDR : constant Enum := 16#043F#; IL_ICNS : constant Enum := 16#0440#; IL_JP2 : constant Enum := 16#0441#; IL_EXR : constant Enum := 16#0442#; IL_WDP : constant Enum := 16#0443#; IL_VTF : constant Enum := 16#0444#; IL_WBMP : constant Enum := 16#0445#; IL_SUN : constant Enum := 16#0446#; IL_IFF : constant Enum := 16#0447#; IL_TPL : constant Enum := 16#0448#; IL_FITS : constant Enum := 16#0449#; IL_DICOM : constant Enum := 16#044A#; IL_IWI : constant Enum := 16#044B#; IL_BLP : constant Enum := 16#044C#; IL_FTX : constant Enum := 16#044D#; IL_ROT : constant Enum := 16#044E#; IL_TEXTURE : constant Enum := 16#044F#; IL_DPX : constant Enum := 16#0450#; IL_UTX : constant Enum := 16#0451#; IL_MP3 : constant Enum := 16#0452#; IL_JASC_PAL : constant Enum := 16#0475#; -- Types of errors. IL_NO_ERROR : constant Enum := 16#0000#; IL_INVALID_ENUM : constant Enum := 16#0501#; IL_OUT_OF_MEMORY : constant Enum := 16#0502#; IL_FORMAT_NOT_SUPPORTED : constant Enum := 16#0503#; IL_INTERNAL_ERROR : constant Enum := 16#0504#; IL_INVALID_VALUE : constant Enum := 16#0505#; IL_ILLEGAL_OPERATION : constant Enum := 16#0506#; IL_ILLEGAL_FILE_VALUE : constant Enum := 16#0507#; IL_INVALID_FILE_HEADER : constant Enum := 16#0508#; IL_INVALID_PARAM : constant Enum := 16#0509#; IL_COULD_NOT_OPEN_FILE : constant Enum := 16#050A#; IL_INVALID_EXTENSION : constant Enum := 16#050B#; IL_FILE_ALREADY_EXISTS : constant Enum := 16#050C#; IL_OUT_FORMAT_SAME : constant Enum := 16#050D#; IL_STACK_OVERFLOW : constant Enum := 16#050E#; IL_STACK_UNDERFLOW : constant Enum := 16#050F#; IL_INVALID_CONVERSION : constant Enum := 16#0510#; IL_BAD_DIMENSIONS : constant Enum := 16#0511#; IL_FILE_READ_ERROR : constant Enum := 16#0512#; IL_FILE_WRITE_ERROR : constant Enum := 16#0513#; IL_LIB_GIF_ERROR : constant Enum := 16#05E1#; IL_LIB_JPEG_ERROR : constant Enum := 16#05E2#; IL_LIB_PNG_ERROR : constant Enum := 16#05E3#; IL_LIB_TIFF_ERROR : constant Enum := 16#05E4#; IL_LIB_MNG_ERROR : constant Enum := 16#05E5#; IL_LIB_JP2_ERROR : constant Enum := 16#05E6#; IL_LIB_EXR_ERROR : constant Enum := 16#05E7#; IL_UNKNOWN_ERROR : constant Enum := 16#05FF#; -- Origin definitions. IL_ORIGIN_SET : constant Enum := 16#0600#; IL_ORIGIN_LOWER_LEFT : constant Enum := 16#0601#; IL_ORIGIN_UPPER_LEFT : constant Enum := 16#0602#; IL_ORIGIN_MODE : constant Enum := 16#0603#; -- Format and type mode definitions. IL_FORMAT_SET : constant Enum := 16#0610#; IL_FORMAT_MODE : constant Enum := 16#0611#; IL_TYPE_SET : constant Enum := 16#0612#; IL_TYPE_MODE : constant Enum := 16#0613#; -- File definitions. IL_FILE_OVERWRITE : constant Enum := 16#0620#; IL_FILE_MODE : constant Enum := 16#0621#; -- Palette difinitions. IL_CONV_PAL : constant Enum := 16#0630#; -- Load fail definitions. IL_DEFAULT_ON_FAIL : constant Enum := 16#0632#; -- Key colour and alpha definitions. IL_USE_KEY_COLOUR : constant Enum := 16#0635#; IL_USE_KEY_COLOR : constant Enum := 16#0635#; IL_BLIT_BLEND : constant Enum := 16#0636#; -- Interlace definitions. IL_SAVE_INTERLACED : constant Enum := 16#0639#; IL_INTERLACE_MODE : constant Enum := 16#063A#; -- Quantization definitions. IL_QUANTIZATION_MODE : constant Enum := 16#0640#; IL_WU_QUANT : constant Enum := 16#0641#; IL_NEU_QUANT : constant Enum := 16#0642#; IL_NEU_QUANT_SAMPLE : constant Enum := 16#0643#; IL_MAX_QUANT_INDEXS : constant Enum := 16#0644#; IL_MAX_QUANT_INDICES : constant Enum := 16#0644#; -- Hints. IL_FASTEST : constant Enum := 16#0660#; IL_LESS_MEM : constant Enum := 16#0661#; IL_DONT_CARE : constant Enum := 16#0662#; IL_MEM_SPEED_HINT : constant Enum := 16#0665#; IL_USE_COMPRESSION : constant Enum := 16#0666#; IL_NO_COMPRESSION : constant Enum := 16#0667#; IL_COMPRESSION_HINT : constant Enum := 16#0668#; -------------------------------------------------------------------------- end Imago.IL;
Add additional definitions.
Add additional definitions. Signed-off-by: darkestkhan <[email protected]>
Ada
isc
darkestkhan/imago
0cbc539a5a9af51415f0ffac20d9b5cd05e69cb8
src/security-auth.adb
src/security-auth.adb
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Security.Auth.OpenID; with Security.Auth.OAuth.Facebook; with Security.Auth.OAuth.Googleplus; package body Security.Auth is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth"); -- ------------------------------ -- Get the provider. -- ------------------------------ function Get_Provider (Assoc : in Association) return String is begin return To_String (Assoc.Provider); end Get_Provider; -- ------------------------------ -- Get the email address -- ------------------------------ function Get_Email (Auth : in Authentication) return String is begin return To_String (Auth.Email); end Get_Email; -- ------------------------------ -- Get the user first name. -- ------------------------------ function Get_First_Name (Auth : in Authentication) return String is begin return To_String (Auth.First_Name); end Get_First_Name; -- ------------------------------ -- Get the user last name. -- ------------------------------ function Get_Last_Name (Auth : in Authentication) return String is begin return To_String (Auth.Last_Name); end Get_Last_Name; -- ------------------------------ -- Get the user full name. -- ------------------------------ function Get_Full_Name (Auth : in Authentication) return String is begin return To_String (Auth.Full_Name); end Get_Full_Name; -- ------------------------------ -- Get the user identity. -- ------------------------------ function Get_Identity (Auth : in Authentication) return String is begin return To_String (Auth.Identity); end Get_Identity; -- ------------------------------ -- Get the user claimed identity. -- ------------------------------ function Get_Claimed_Id (Auth : in Authentication) return String is begin return To_String (Auth.Claimed_Id); end Get_Claimed_Id; -- ------------------------------ -- Get the user language. -- ------------------------------ function Get_Language (Auth : in Authentication) return String is begin return To_String (Auth.Language); end Get_Language; -- ------------------------------ -- Get the user country. -- ------------------------------ function Get_Country (Auth : in Authentication) return String is begin return To_String (Auth.Country); end Get_Country; -- ------------------------------ -- Get the result of the authentication. -- ------------------------------ function Get_Status (Auth : in Authentication) return Auth_Result is begin return Auth.Status; end Get_Status; -- ------------------------------ -- Default principal -- ------------------------------ -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth); end Get_Name; -- ------------------------------ -- Get the user email address. -- ------------------------------ function Get_Email (From : in Principal) return String is begin return Get_Email (From.Auth); end Get_Email; -- ------------------------------ -- Get the authentication data. -- ------------------------------ function Get_Authentication (From : in Principal) return Authentication is begin return From.Auth; end Get_Authentication; -- ------------------------------ -- Create a principal with the given authentication results. -- ------------------------------ function Create_Principal (Auth : in Authentication) return Principal_Access is P : constant Principal_Access := new Principal; begin P.Auth := Auth; return P; end Create_Principal; -- ------------------------------ -- Initialize the OpenID realm. -- ------------------------------ procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID) is Provider : constant String := Params.Get_Parameter ("auth.provider." & Name); Impl : Manager_Access; begin if Provider = PROVIDER_OPENID then Impl := new Security.Auth.OpenID.Manager; elsif Provider = PROVIDER_FACEBOOK then Impl := new Security.Auth.OAuth.Facebook.Manager; elsif Provider = PROVIDER_GOOGLE_PLUS then Impl := new Security.Auth.OAuth.Googleplus.Manager; else Log.Error ("Authentication provider {0} not recognized", Provider); raise Service_Error with "Authentication provider not supported"; end if; Realm.Delegate := Impl; Impl.Initialize (Params, Name); Realm.Provider := To_Unbounded_String (Name); end Initialize; -- ------------------------------ -- 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) is begin if Realm.Delegate /= null then Realm.Delegate.Discover (Name, Result); else -- Result.URL := Realm.Realm; Result.Alias := To_Unbounded_String (""); end if; end Discover; -- ------------------------------ -- 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) is begin Result.Provider := Realm.Provider; if Realm.Delegate /= null then Realm.Delegate.Associate (OP, Result); end if; end Associate; -- ------------------------------ -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. -- ------------------------------ function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String is begin if Realm.Delegate /= null then return Realm.Delegate.Get_Authentication_URL (OP, Assoc); else return To_String (OP.URL); end if; end Get_Authentication_URL; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String) is begin if Status /= AUTHENTICATED then Log.Error ("OpenID verification failed: {0}", Message); else Log.Info ("OpenID verification: {0}", Message); end if; Result.Status := Status; end Set_Result; -- ------------------------------ -- Verify the authentication result -- ------------------------------ procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication) is begin if Realm.Delegate /= null then Realm.Delegate.Verify (Assoc, Request, Result); else Set_Result (Result, SETUP_NEEDED, "Setup is needed"); end if; end Verify; function To_String (OP : End_Point) return String is begin return "openid://" & To_String (OP.URL); end To_String; function To_String (Assoc : Association) return String is begin return "session_type=" & To_String (Assoc.Session_Type) & "&assoc_type=" & To_String (Assoc.Assoc_Type) & "&assoc_handle=" & To_String (Assoc.Assoc_Handle) & "&mac_key=" & To_String (Assoc.Mac_Key); end To_String; end Security.Auth;
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Security.Auth.OpenID; with Security.Auth.OAuth.Facebook; with Security.Auth.OAuth.Googleplus; package body Security.Auth is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth"); -- ------------------------------ -- Get the provider. -- ------------------------------ function Get_Provider (Assoc : in Association) return String is begin return To_String (Assoc.Provider); end Get_Provider; -- ------------------------------ -- Get the email address -- ------------------------------ function Get_Email (Auth : in Authentication) return String is begin return To_String (Auth.Email); end Get_Email; -- ------------------------------ -- Get the user first name. -- ------------------------------ function Get_First_Name (Auth : in Authentication) return String is begin return To_String (Auth.First_Name); end Get_First_Name; -- ------------------------------ -- Get the user last name. -- ------------------------------ function Get_Last_Name (Auth : in Authentication) return String is begin return To_String (Auth.Last_Name); end Get_Last_Name; -- ------------------------------ -- Get the user full name. -- ------------------------------ function Get_Full_Name (Auth : in Authentication) return String is begin return To_String (Auth.Full_Name); end Get_Full_Name; -- ------------------------------ -- Get the user identity. -- ------------------------------ function Get_Identity (Auth : in Authentication) return String is begin return To_String (Auth.Identity); end Get_Identity; -- ------------------------------ -- Get the user claimed identity. -- ------------------------------ function Get_Claimed_Id (Auth : in Authentication) return String is begin return To_String (Auth.Claimed_Id); end Get_Claimed_Id; -- ------------------------------ -- Get the user language. -- ------------------------------ function Get_Language (Auth : in Authentication) return String is begin return To_String (Auth.Language); end Get_Language; -- ------------------------------ -- Get the user country. -- ------------------------------ function Get_Country (Auth : in Authentication) return String is begin return To_String (Auth.Country); end Get_Country; -- ------------------------------ -- Get the result of the authentication. -- ------------------------------ function Get_Status (Auth : in Authentication) return Auth_Result is begin return Auth.Status; end Get_Status; -- ------------------------------ -- Default principal -- ------------------------------ -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth); end Get_Name; -- ------------------------------ -- Get the user email address. -- ------------------------------ function Get_Email (From : in Principal) return String is begin return Get_Email (From.Auth); end Get_Email; -- ------------------------------ -- Get the authentication data. -- ------------------------------ function Get_Authentication (From : in Principal) return Authentication is begin return From.Auth; end Get_Authentication; -- ------------------------------ -- Create a principal with the given authentication results. -- ------------------------------ function Create_Principal (Auth : in Authentication) return Principal_Access is P : constant Principal_Access := new Principal; begin P.Auth := Auth; return P; end Create_Principal; -- ------------------------------ -- Default factory used by `Initialize`. It supports OpenID, Google, Facebook. -- ------------------------------ function Default_Factory (Provider : in String) return Manager_Access is begin if Provider = PROVIDER_OPENID then return new Security.Auth.OpenID.Manager; elsif Provider = PROVIDER_FACEBOOK then return new Security.Auth.OAuth.Facebook.Manager; elsif Provider = PROVIDER_GOOGLE_PLUS then return new Security.Auth.OAuth.Googleplus.Manager; else Log.Error ("Authentication provider {0} not recognized", Provider); raise Service_Error with "Authentication provider not supported"; end if; end Default_Factory; -- ------------------------------ -- Initialize the OpenID realm. -- ------------------------------ procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID) is begin Initialize (Realm, Params, Default_Factory'Access, Name); end Initialize; procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Factory : not null access function (Name : in String) return Manager_Access; Name : in String := PROVIDER_OPENID) is Provider : constant String := Params.Get_Parameter ("auth.provider." & Name); Impl : constant Manager_Access := Factory (Provider); begin if Impl = null then Log.Error ("Authentication provider {0} not recognized", Provider); raise Service_Error with "Authentication provider not supported"; end if; Realm.Delegate := Impl; Impl.Initialize (Params, Name); Realm.Provider := To_Unbounded_String (Name); end Initialize; -- ------------------------------ -- 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) is begin if Realm.Delegate /= null then Realm.Delegate.Discover (Name, Result); else -- Result.URL := Realm.Realm; Result.Alias := To_Unbounded_String (""); end if; end Discover; -- ------------------------------ -- 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) is begin Result.Provider := Realm.Provider; if Realm.Delegate /= null then Realm.Delegate.Associate (OP, Result); end if; end Associate; -- ------------------------------ -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. -- ------------------------------ function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String is begin if Realm.Delegate /= null then return Realm.Delegate.Get_Authentication_URL (OP, Assoc); else return To_String (OP.URL); end if; end Get_Authentication_URL; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String) is begin if Status /= AUTHENTICATED then Log.Error ("OpenID verification failed: {0}", Message); else Log.Info ("OpenID verification: {0}", Message); end if; Result.Status := Status; end Set_Result; -- ------------------------------ -- Verify the authentication result -- ------------------------------ procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication) is begin if Realm.Delegate /= null then Realm.Delegate.Verify (Assoc, Request, Result); else Set_Result (Result, SETUP_NEEDED, "Setup is needed"); end if; end Verify; function To_String (OP : End_Point) return String is begin return "openid://" & To_String (OP.URL); end To_String; function To_String (Assoc : Association) return String is begin return "session_type=" & To_String (Assoc.Session_Type) & "&assoc_type=" & To_String (Assoc.Assoc_Type) & "&assoc_handle=" & To_String (Assoc.Assoc_Handle) & "&mac_key=" & To_String (Assoc.Mac_Key); end To_String; end Security.Auth;
Add Default_Factory function and new Initialize procedure to allow adding new OAuth providers more easily
Add Default_Factory function and new Initialize procedure to allow adding new OAuth providers more easily
Ada
apache-2.0
stcarrez/ada-security
dcf7911dea063f9d6766c0ae9dec7ec4cc05d0e1
tests/natools-s_expressions-conditionals-strings-tests.adb
tests/natools-s_expressions-conditionals-strings-tests.adb
------------------------------------------------------------------------------ -- Copyright (c) 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.Caches; with Natools.S_Expressions.Test_Tools; package body Natools.S_Expressions.Conditionals.Strings.Tests is procedure Check (Test : in out NT.Test; Context : in Strings.Context; Expression : in Caches.Reference; Image : in String; Expected : in Boolean := True); procedure Check (Test : in out NT.Test; Value : in String; Expression : in Caches.Reference; Image : in String; Expected : in Boolean := True); ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Check (Test : in out NT.Test; Context : in Strings.Context; Expression : in Caches.Reference; Image : in String; Expected : in Boolean := True) is function Match_Image return String; Cursor : Caches.Cursor := Expression.First; function Match_Image return String is begin if Expected then return " does not match "; else return " does match "; end if; end Match_Image; begin if Evaluate (Context, Cursor) /= Expected then Test.Fail ('"' & Context.Data.all & '"' & Match_Image & Image); end if; end Check; procedure Check (Test : in out NT.Test; Value : in String; Expression : in Caches.Reference; Image : in String; Expected : in Boolean := True) is function Match_Image return String; Cursor : Caches.Cursor := Expression.First; function Match_Image return String is begin if Expected then return " does not match "; else return " does match "; end if; end Match_Image; begin if Evaluate (Value, Cursor) /= Expected then Test.Fail ('"' & Value & '"' & Match_Image & Image); end if; end Check; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Basic_Usage (Report); Fallbacks (Report); end All_Tests; ---------------------- -- Individual Tests -- ---------------------- procedure Basic_Usage (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Basic usage"); begin declare procedure Check (Value : in String; Expected : in Boolean := True); Image : constant String := "Expression 1"; Exp : constant Caches.Reference := Test_Tools.To_S_Expression ("(or is-empty (starts-with Hi)" & "(and (contains 1:.) (contains-any-of 1:! 1:?))" & "(case-insensitive (or (contains aLiCe)" & " (case-sensitive (contains Bob))))" & "(not is-ascii))"); procedure Check (Value : in String; Expected : in Boolean := True) is begin Check (Test, Value, Exp, Image, Expected); end Check; begin Check (""); Check ("A", False); Check ("Hi, my name is John."); Check ("Hello, my name is John.", False); Check ("Hello. My name is John!"); Check ("Hello. My name is John?"); Check ("Alice and Bob"); Check ("BOBBY!", False); Check ("AlicE and Malory"); Check ("©"); end; exception when Error : others => Test.Report_Exception (Error); end Basic_Usage; procedure Fallbacks (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Fallback functions"); begin declare procedure Check (Value : in String; With_Fallback : in Boolean); procedure Check_Counts (Expected_Parametric, Expected_Simple : in Natural); function Parametric_Fallback (Settings : in Strings.Settings; Name : in Atom; Arguments : in out Lockable.Descriptor'Class) return Boolean; function Simple_Fallback (Settings : in Strings.Settings; Name : in Atom) return Boolean; Parametric_Count : Natural := 0; Simple_Count : Natural := 0; Exp : constant Caches.Reference := Test_Tools.To_S_Expression ("(or" & "(and (starts-with a) non-existant)" & "(does-not-exist ohai ()))"); procedure Check (Value : in String; With_Fallback : in Boolean) is Copy : aliased constant String := Value; Context : Strings.Context (Data => Copy'Access, Parametric_Fallback => (if With_Fallback then Parametric_Fallback'Access else null), Simple_Fallback => (if With_Fallback then Simple_Fallback'Access else null)); begin Context.Settings.Case_Sensitive := False; begin Check (Test, Context, Exp, "Fallback expression"); if not With_Fallback then Test.Fail ("Exception expected from """ & Value & '"'); end if; exception when Constraint_Error => if With_Fallback then raise; end if; end; end Check; procedure Check_Counts (Expected_Parametric, Expected_Simple : in Natural) is begin if Parametric_Count /= Expected_Parametric then Test.Fail ("Parametric_Count is" & Natural'Image (Parametric_Count) & ", expected" & Natural'Image (Expected_Parametric)); end if; if Simple_Count /= Expected_Simple then Test.Fail ("Simple_Count is" & Natural'Image (Simple_Count) & ", expected" & Natural'Image (Expected_Simple)); end if; end Check_Counts; function Parametric_Fallback (Settings : in Strings.Settings; Name : in Atom; Arguments : in out Lockable.Descriptor'Class) return Boolean is pragma Unreferenced (Settings, Arguments); begin Parametric_Count := Parametric_Count + 1; return To_String (Name) = "does-not-exist"; end Parametric_Fallback; function Simple_Fallback (Settings : in Strings.Settings; Name : in Atom) return Boolean is pragma Unreferenced (Settings); begin Simple_Count := Simple_Count + 1; return To_String (Name) = "non-existant"; end Simple_Fallback; begin Check ("Oook?", False); Check ("Alice", False); Check ("Alpha", True); Check_Counts (0, 1); Check ("Bob", True); Check_Counts (1, 1); end; exception when Error : others => Test.Report_Exception (Error); end Fallbacks; end Natools.S_Expressions.Conditionals.Strings.Tests;
------------------------------------------------------------------------------ -- Copyright (c) 2015-2017, 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.Caches; with Natools.S_Expressions.Test_Tools; package body Natools.S_Expressions.Conditionals.Strings.Tests is procedure Check (Test : in out NT.Test; Context : in Strings.Context; Expression : in Caches.Reference; Image : in String; Expected : in Boolean := True); procedure Check (Test : in out NT.Test; Value : in String; Expression : in Caches.Reference; Image : in String; Expected : in Boolean := True); ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Check (Test : in out NT.Test; Context : in Strings.Context; Expression : in Caches.Reference; Image : in String; Expected : in Boolean := True) is function Match_Image return String; Cursor : Caches.Cursor := Expression.First; function Match_Image return String is begin if Expected then return " does not match "; else return " does match "; end if; end Match_Image; begin if Evaluate (Context, Cursor) /= Expected then Test.Fail ('"' & Context.Data.all & '"' & Match_Image & Image); end if; end Check; procedure Check (Test : in out NT.Test; Value : in String; Expression : in Caches.Reference; Image : in String; Expected : in Boolean := True) is function Match_Image return String; Cursor : Caches.Cursor := Expression.First; function Match_Image return String is begin if Expected then return " does not match "; else return " does match "; end if; end Match_Image; begin if Evaluate (Value, Cursor) /= Expected then Test.Fail ('"' & Value & '"' & Match_Image & Image); end if; end Check; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Basic_Usage (Report); Fallbacks (Report); end All_Tests; ---------------------- -- Individual Tests -- ---------------------- procedure Basic_Usage (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Basic usage"); begin declare procedure Check (Value : in String; Expected : in Boolean := True); Image : constant String := "Expression 1"; Exp : constant Caches.Reference := Test_Tools.To_S_Expression ("(or is-empty (starts-with Hi)" & "(is BY) (case-insensitive (is HELLO))" & "(and (contains 1:.) (contains-any-of 1:! 1:?))" & "(case-insensitive (or (contains aLiCe)" & " (case-sensitive (contains Bob))))" & "(not is-ascii))"); procedure Check (Value : in String; Expected : in Boolean := True) is begin Check (Test, Value, Exp, Image, Expected); end Check; begin Check (""); Check ("A", False); Check ("Hi, my name is John."); Check ("Hello, my name is John.", False); Check ("Hello. My name is John!"); Check ("Hello. My name is John?"); Check ("Alice and Bob"); Check ("BOBBY!", False); Check ("AlicE and Malory"); Check ("©"); Check ("BY"); Check ("By", False); Check ("Hello"); Check ("Hell", False); end; exception when Error : others => Test.Report_Exception (Error); end Basic_Usage; procedure Fallbacks (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Fallback functions"); begin declare procedure Check (Value : in String; With_Fallback : in Boolean); procedure Check_Counts (Expected_Parametric, Expected_Simple : in Natural); function Parametric_Fallback (Settings : in Strings.Settings; Name : in Atom; Arguments : in out Lockable.Descriptor'Class) return Boolean; function Simple_Fallback (Settings : in Strings.Settings; Name : in Atom) return Boolean; Parametric_Count : Natural := 0; Simple_Count : Natural := 0; Exp : constant Caches.Reference := Test_Tools.To_S_Expression ("(or" & "(and (starts-with a) non-existant)" & "(does-not-exist ohai ()))"); procedure Check (Value : in String; With_Fallback : in Boolean) is Copy : aliased constant String := Value; Context : Strings.Context (Data => Copy'Access, Parametric_Fallback => (if With_Fallback then Parametric_Fallback'Access else null), Simple_Fallback => (if With_Fallback then Simple_Fallback'Access else null)); begin Context.Settings.Case_Sensitive := False; begin Check (Test, Context, Exp, "Fallback expression"); if not With_Fallback then Test.Fail ("Exception expected from """ & Value & '"'); end if; exception when Constraint_Error => if With_Fallback then raise; end if; end; end Check; procedure Check_Counts (Expected_Parametric, Expected_Simple : in Natural) is begin if Parametric_Count /= Expected_Parametric then Test.Fail ("Parametric_Count is" & Natural'Image (Parametric_Count) & ", expected" & Natural'Image (Expected_Parametric)); end if; if Simple_Count /= Expected_Simple then Test.Fail ("Simple_Count is" & Natural'Image (Simple_Count) & ", expected" & Natural'Image (Expected_Simple)); end if; end Check_Counts; function Parametric_Fallback (Settings : in Strings.Settings; Name : in Atom; Arguments : in out Lockable.Descriptor'Class) return Boolean is pragma Unreferenced (Settings, Arguments); begin Parametric_Count := Parametric_Count + 1; return To_String (Name) = "does-not-exist"; end Parametric_Fallback; function Simple_Fallback (Settings : in Strings.Settings; Name : in Atom) return Boolean is pragma Unreferenced (Settings); begin Simple_Count := Simple_Count + 1; return To_String (Name) = "non-existant"; end Simple_Fallback; begin Check ("Oook?", False); Check ("Alice", False); Check ("Alpha", True); Check_Counts (0, 1); Check ("Bob", True); Check_Counts (1, 1); end; exception when Error : others => Test.Report_Exception (Error); end Fallbacks; end Natools.S_Expressions.Conditionals.Strings.Tests;
test the new equality test
s_expressions-conditionals-strings-tests: test the new equality test
Ada
isc
faelys/natools
4aa628b2af4a47c68d19a0a204d4f03cd3dab1d0
src/util-log.ads
src/util-log.ads
----------------------------------------------------------------------- -- Logs -- Utility Log Package -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- = Logging = -- The `Util.Log` package and children provide a simple logging framework inspired -- from the Java Log4j library. It is intended to provide a subset of logging features -- available in other languages, be flexible, extensible, small and efficient. Having -- log messages in large applications is very helpful to understand, track and fix complex -- issues, some of them being related to configuration issues or interaction with other -- systems. The overhead of calling a log operation is negligeable when the log is disabled -- as it is in the order of 30ns and reasonable for a file appender has it is in the order -- of 5us. -- -- == Using the log framework == -- A bit of terminology: -- -- * A *logger* is the abstraction that provides operations to emit a message. The message -- is composed of a text, optional formatting parameters, a log level and a timestamp. -- * A *formatter* is the abstraction that takes the information about the log to format -- the final message. -- * An *appender* is the abstraction that writes the message either to a console, a file -- or some other final mechanism. -- -- === Logger Declaration === -- Similar to other logging framework such as Log4j and Log4cxx, it is necessary to have -- and instance of a logger to write a log message. The logger instance holds the configuration -- for the log to enable, disable and control the format and the appender that will receive -- the message. The logger instance is associated with a name that is used for the -- configuration. A good practice is to declare a `Log` instance in the package body or -- the package private part to make available the log instance to all the package operations. -- The instance is created by using the `Create` function. The name used for the configuration -- is free but using the full package name is helpful to control precisely the logs. -- -- with Util.Log.Loggers; -- package body X.Y is -- Log : constant Util.Log.Loggers := Util.Log.Loggers.Create ("X.Y"); -- end X.Y; -- -- === Logger Messages === -- A log message is associated with a log level which is used by the logger instance to -- decide to emit or drop the log message. To keep the logging API simple and make it easily -- usable in the application, several operations are provided to write a message with different -- log level. -- -- A log message is a string that contains optional formatting markers that follow more or -- less the Java MessageFormat class. A parameter is represented by a number enclosed by `{}`. -- The first parameter is represented by `{0}`, the second by `{1}` and so on. -- -- The example below shows several calls to emit a log message with different levels: -- -- Log.Error ("Cannot open file {0}: {1}", Path, "File does not exist"); -- Log.Warn ("The file {0} is empty", Path); -- Log.Info ("Opening file {0}", Path); -- Log.Debug ("Reading line {0}", Line); -- -- === Log Configuration === -- The log configuration uses property files close to the Apache Log4j and to the -- Apache Log4cxx configuration files. -- The configuration file contains several parts to configure the logging framework: -- -- * First, the *appender* configuration indicates the appender that exists and can receive -- a log message. -- * Second, a root configuration allows to control the default behavior of the logging -- framework. The root configuration controls the default log level as well as the -- appenders that can be used. -- * Last, a logger configuration is defined to control the logging level more precisely -- for each logger. -- -- Here is a simple log configuration that creates a file appender where log messages are -- written. The file appender is given the name `result` and is configured to write the -- messages in the file `my-log-file.log`. The file appender will use the `level-message` -- format for the layout of messages. Last is the configuration of the `X.Y` logger -- that will enable only messages starting from the `WARN` level. -- -- log4j.rootCategory=DEBUG,result -- log4j.appender.result=File -- log4j.appender.result.File=my-log-file.log -- log4j.appender.result.layout=level-message -- log4j.logger.X.Y=WARN -- -- package Util.Log is pragma Preelaborate; subtype Level_Type is Natural; FATAL_LEVEL : constant Level_Type := 0; ERROR_LEVEL : constant Level_Type := 5; WARN_LEVEL : constant Level_Type := 7; INFO_LEVEL : constant Level_Type := 10; DEBUG_LEVEL : constant Level_Type := 20; -- Get the log level name. function Get_Level_Name (Level : Level_Type) return String; -- Get the log level from the property value function Get_Level (Value : in String; Default : in Level_Type := INFO_LEVEL) return Level_Type; -- The <tt>Logging</tt> interface defines operations that can be implemented for a -- type to report errors or messages. type Logging is limited interface; procedure Error (Log : in out Logging; Message : in String) is abstract; end Util.Log;
----------------------------------------------------------------------- -- util-log -- Utility Log Package -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- = Logging = -- The `Util.Log` package and children provide a simple logging framework inspired -- from the Java Log4j library. It is intended to provide a subset of logging features -- available in other languages, be flexible, extensible, small and efficient. Having -- log messages in large applications is very helpful to understand, track and fix complex -- issues, some of them being related to configuration issues or interaction with other -- systems. The overhead of calling a log operation is negligeable when the log is disabled -- as it is in the order of 30ns and reasonable for a file appender has it is in the order -- of 5us. -- -- == Using the log framework == -- A bit of terminology: -- -- * A *logger* is the abstraction that provides operations to emit a message. The message -- is composed of a text, optional formatting parameters, a log level and a timestamp. -- * A *formatter* is the abstraction that takes the information about the log to format -- the final message. -- * An *appender* is the abstraction that writes the message either to a console, a file -- or some other final mechanism. -- -- === Logger Declaration === -- Similar to other logging framework such as Log4j and Log4cxx, it is necessary to have -- and instance of a logger to write a log message. The logger instance holds the configuration -- for the log to enable, disable and control the format and the appender that will receive -- the message. The logger instance is associated with a name that is used for the -- configuration. A good practice is to declare a `Log` instance in the package body or -- the package private part to make available the log instance to all the package operations. -- The instance is created by using the `Create` function. The name used for the configuration -- is free but using the full package name is helpful to control precisely the logs. -- -- with Util.Log.Loggers; -- package body X.Y is -- Log : constant Util.Log.Loggers := Util.Log.Loggers.Create ("X.Y"); -- end X.Y; -- -- === Logger Messages === -- A log message is associated with a log level which is used by the logger instance to -- decide to emit or drop the log message. To keep the logging API simple and make it easily -- usable in the application, several operations are provided to write a message with different -- log level. -- -- A log message is a string that contains optional formatting markers that follow more or -- less the Java MessageFormat class. A parameter is represented by a number enclosed by `{}`. -- The first parameter is represented by `{0}`, the second by `{1}` and so on. -- -- The example below shows several calls to emit a log message with different levels: -- -- Log.Error ("Cannot open file {0}: {1}", Path, "File does not exist"); -- Log.Warn ("The file {0} is empty", Path); -- Log.Info ("Opening file {0}", Path); -- Log.Debug ("Reading line {0}", Line); -- -- === Log Configuration === -- The log configuration uses property files close to the Apache Log4j and to the -- Apache Log4cxx configuration files. -- The configuration file contains several parts to configure the logging framework: -- -- * First, the *appender* configuration indicates the appender that exists and can receive -- a log message. -- * Second, a root configuration allows to control the default behavior of the logging -- framework. The root configuration controls the default log level as well as the -- appenders that can be used. -- * Last, a logger configuration is defined to control the logging level more precisely -- for each logger. -- -- Here is a simple log configuration that creates a file appender where log messages are -- written. The file appender is given the name `result` and is configured to write the -- messages in the file `my-log-file.log`. The file appender will use the `level-message` -- format for the layout of messages. Last is the configuration of the `X.Y` logger -- that will enable only messages starting from the `WARN` level. -- -- log4j.rootCategory=DEBUG,result -- log4j.appender.result=File -- log4j.appender.result.File=my-log-file.log -- log4j.appender.result.layout=level-message -- log4j.logger.X.Y=WARN -- -- package Util.Log is pragma Preelaborate; subtype Level_Type is Natural; FATAL_LEVEL : constant Level_Type := 0; ERROR_LEVEL : constant Level_Type := 5; WARN_LEVEL : constant Level_Type := 7; INFO_LEVEL : constant Level_Type := 10; DEBUG_LEVEL : constant Level_Type := 20; -- Get the log level name. function Get_Level_Name (Level : Level_Type) return String; -- Get the log level from the property value function Get_Level (Value : in String; Default : in Level_Type := INFO_LEVEL) return Level_Type; -- The <tt>Logging</tt> interface defines operations that can be implemented for a -- type to report errors or messages. type Logging is limited interface; procedure Error (Log : in out Logging; Message : in String) is abstract; end Util.Log;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7a35fe96b94a3b8fa0fca565975174731084a954
matp/src/events/mat-events-timelines.ads
matp/src/events/mat-events-timelines.ads
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with MAT.Expressions; with MAT.Events.Tools; with MAT.Events.Targets; package MAT.Events.Timelines is -- Describe a section of the timeline. The section has a starting and ending -- event that marks the boundary of the section within the collected events. -- The timeline section gives the duration and some statistics about memory -- allocation made in the section. type Timeline_Info is record First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Duration : MAT.Types.Target_Time := 0; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 0; Alloc_Size : MAT.Types.Target_Size := 0; Free_Size : MAT.Types.Target_Size := 0; end record; package Timeline_Info_Vectors is new Ada.Containers.Vectors (Positive, Timeline_Info); subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector; subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Into : in out Timeline_Info_Vector); -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector); -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map); -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Natural; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map); end MAT.Events.Timelines;
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with MAT.Expressions; with MAT.Events.Tools; with MAT.Events.Targets; package MAT.Events.Timelines is -- Describe a section of the timeline. The section has a starting and ending -- event that marks the boundary of the section within the collected events. -- The timeline section gives the duration and some statistics about memory -- allocation made in the section. type Timeline_Info is record First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Duration : MAT.Types.Target_Time := 0; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 0; Alloc_Size : MAT.Types.Target_Size := 0; Free_Size : MAT.Types.Target_Size := 0; end record; package Timeline_Info_Vectors is new Ada.Containers.Vectors (Positive, Timeline_Info); subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector; subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Into : in out Timeline_Info_Vector); -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector); -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map); -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Positive; Exact : in Boolean; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map); end MAT.Events.Timelines;
Add the Exact boolean paramter to Find_Frames to take into account only the stack frames at the given depth level
Add the Exact boolean paramter to Find_Frames to take into account only the stack frames at the given depth level
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8e688ab95f3e4dd0568764e53c7b837e01ddcfa5
ARM/STMicro/STM32/examples/balls/src/demo.adb
ARM/STMicro/STM32/examples/balls/src/demo.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- The file declares the main procedure for the demonstration. The LEDs -- will blink "in a circle" on the board. The blue user button generates -- an interrupt that changes the direction. with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); -- The "last chance handler" is the user-defined routine that is called when -- an exception is propagated. We need it in the executable, therefore it -- must be somewhere in the closure of the context clauses. with System; with Interfaces; use Interfaces; with STM32.Button; use STM32.Button; with STM32.LCD; use STM32.LCD; with STM32.DMA2D.Interrupt; use STM32.DMA2D; with STM32.RNG.Interrupts; use STM32.RNG.Interrupts; with Bitmapped_Drawing; use Bitmapped_Drawing; with Double_Buffer; use Double_Buffer; procedure Demo is use STM32; pragma Priority (System.Priority'First); type HSV_Color is record Hue : Byte; Sat : Byte; Val : Byte; end record; function To_RGB (Col : HSV_Color) return DMA2D_Color; -- Translates a Hue/Saturation/Value color into RGB type Coordinate is (X, Y); type Vector is array (Coordinate) of Float; function "+" (V1, V2 : Vector) return Vector is begin return (X => V1 (X) + V2 (X), Y => V1 (Y) + V2 (Y)); end "+"; function "-" (V1, V2 : Vector) return Vector is begin return (X => V1 (X) - V2 (X), Y => V1 (Y) - V2 (Y)); end "-"; function "*" (V1, V2 : Vector) return Float is begin return V1 (X) * V2 (X) + V1 (Y) * V2 (Y); end "*"; function "*" (V : Vector; Val : Float) return Vector is begin return (V (X) * Val, V (Y) * Val); end "*"; function "/" (V : Vector; Val : Float) return Vector is begin return (V (X) / Val, V (Y) / Val); end "/"; type Moving_Object is record Center : Vector; Speed : Vector; R : Natural; Col : HSV_Color; N_Hue : Byte; end record; function I (F : Float) return Integer is (Integer (F)); function Collides (M1, M2 : Moving_Object) return Boolean; procedure Handle_Collision (M1, M2 : in out Moving_Object); Objects : array (1 .. 15) of Moving_Object; FG_Buffer : DMA2D_Buffer; White_Background : Boolean := False; ------------ -- To_RGB -- ------------ function To_RGB (Col : HSV_Color) return DMA2D_Color is V, S, H : Word; Region, FPart, p, q, t : Word; Ret : DMA2D_Color; begin Ret.Alpha := 255; if Col.Sat = 0 then Ret.Red := Col.Val; Ret.Green := Col.Val; Ret.Blue := Col.Val; return Ret; end if; V := Word (Col.Val); S := Word (Col.Sat); H := Word (Col.Hue); -- Hue in the range 0 .. 5 Region := H / 43; -- Division reminder, multiplied by 6 to make it in range 0 .. 255 FPart := (H - (Region * 43)) * 6; P := Shift_Right (V * (255 - S), 8); Q := Shift_Right (V * (255 - Shift_Right (S * FPart, 8)), 8); T := Shift_Right (V * (255 - Shift_Right (S * (255 - FPart), 8)), 8); case Region is when 0 => Ret.Red := Byte (V); Ret.Green := Byte (T); Ret.Blue := Byte (P); when 1 => Ret.Red := Byte (Q); Ret.Green := Byte (V); Ret.Blue := Byte (P); when 2 => Ret.Red := Byte (P); Ret.Green := Byte (V); Ret.Blue := Byte (T); when 3 => Ret.Red := Byte (P); Ret.Green := Byte (Q); Ret.Blue := Byte (V); when 4 => Ret.Red := Byte (T); Ret.Green := Byte (P); Ret.Blue := Byte (V); when others => Ret.Red := Byte (V); Ret.Green := Byte (P); Ret.Blue := Byte (Q); end case; return Ret; end To_RGB; ------------- -- Colides -- ------------- function Collides (M1, M2 : Moving_Object) return Boolean is Dist_Min_Square : constant Integer := (M1.R + M2.R) ** 2; M1_M2 : constant Vector := M2.Center - M1.Center; Dist_Square : constant Integer := (I (M1_M2 (X)) ** 2 + I (M1_M2 (Y)) ** 2); begin return Dist_Square < Dist_Min_Square; end Collides; ---------------------- -- Handle_Colisiton -- ---------------------- procedure Handle_Collision (M1, M2 : in out Moving_Object) is -- Dist: distance vector between the two objects Dist : Vector; -- Projx: Projection of the speed of Mx on Dist Tmp : Float; Proj1 : Vector; Proj2 : Vector; Tan_Sp1 : Vector; Tan_Sp2 : Vector; Sp1 : Vector; Sp2 : Vector; -- Simplified mass: equal to R^2 Mass1 : constant Float := Float (M1.R ** 2); Mass2 : constant Float := Float (M2.R ** 2); dT : Float := 0.0; Old1, Old2 : Vector; begin -- Move back before collision -- If we don't, then the balls might still be touching themselves -- after we execute this procedure, so collision is called a second -- time afterwards. Old1 := M1.Center; Old2 := M2.Center; loop dT := dT + 0.2; M1.Center := Old1 - M1.Speed * dT; M2.Center := Old2 - M2.Speed * dT; exit when not Collides (M1, M2); end loop; Dist := (M2.Center - M1.Center); -- Calculate the projection vector of the speeds on Dist Tmp := (M1.Speed * Dist) / (Dist * Dist); Proj1 := Dist * Tmp; Tmp := (M2.Speed * Dist) / (Dist * Dist); Proj2 := Dist * Tmp; -- Now retrieve the speed that is tangantial to dist Tan_Sp1 := M1.Speed - Proj1; Tan_Sp2 := M2.Speed - Proj2; -- Transfer the projected speed from one object to the other Sp1 := (Proj1 * (Mass1 - Mass2) + Proj2 * 2.0 * Mass2) / (Mass1 + Mass2); Sp2 := (Proj2 * (Mass2 - Mass1) + Proj1 * 2.0 * Mass1) / (Mass1 + Mass2); -- Calculate the final speed of the objects: -- initial tangantial speed + calculated projected speed M1.Speed := Sp1 + Tan_Sp1; M2.Speed := Sp2 + Tan_Sp2; -- Now replay from the time of the impact with the new speed M1.Center := M1.Center + M1.Speed * dT; M2.Center := M2.Center + M2.Speed * dT; M1.N_Hue := M1.N_Hue + 32; M2.N_Hue := M2.N_Hue + 32; end Handle_Collision; ---------------- -- Init_Balls -- ---------------- procedure Init_Balls is Size : constant Integer := Natural'Min (Pixel_Width, Pixel_Height); R_Min : constant Natural := Size / 24; R_Var : constant Word := Word (R_Min) * 4 / 5; SP_Max : constant Integer := Size / 7; begin for J in Objects'Range loop loop declare O : Moving_Object renames Objects (J); R : constant Integer := Integer (RNG.Interrupts.Random mod R_Var) + R_Min; Col : constant Byte := Byte (RNG.Interrupts.Random mod 255); X_Raw : constant Word := (RNG.Interrupts.Random mod Word (Pixel_Width - 2 * R)) + Word (R); Y_Raw : constant Word := (RNG.Interrupts.Random mod Word (Pixel_Height - 2 * R)) + Word (R); Sp_X : constant Integer := Integer (RNG.Interrupts.Random mod Word (SP_Max * 2 + 1)) - SP_Max; Sp_Y : constant Integer := Integer (RNG.Interrupts.Random mod Word (SP_Max * 2 + 1)) - SP_Max; Redo : Boolean := False; begin O := (Center => (Float (Natural (X_Raw) + R), Float (Natural (Y_Raw) + R)), Speed => (Float (Sp_X) / 10.0, Float (Sp_Y) / 10.0), R => R, Col => (Hue => Col, Sat => 255, Val => 255), N_Hue => Col); for K in Objects'First .. J - 1 loop if Collides (O, Objects (K)) then Redo := True; exit; end if; end loop; exit when not Redo; end; end loop; end loop; end Init_Balls; begin STM32.LCD.Initialize (Pixel_Fmt_ARGB1555); STM32.DMA2D.Interrupt.Initialize; Double_Buffer.Initialize (Layer_Background => Layer_Double_Buffer, Layer_Foreground => Layer_Inactive); STM32.RNG.Interrupts.Initialize_RNG; STM32.Button.Initialize; Init_Balls; loop if STM32.Button.Has_Been_Pressed then White_Background := not White_Background; end if; FG_Buffer := Double_Buffer.Get_Hidden_Buffer (Background); STM32.DMA2D.DMA2D_Fill (FG_Buffer, (if White_Background then White else Black)); for M of Objects loop if M.N_Hue /= M.Col.Hue then M.Col.Hue := M.Col.Hue + 1; end if; end loop; for O of Objects loop O.Center := O.Center + O.Speed; if (O.Speed (X) < 0.0 and then I (O.Center (X)) <= O.R) or else (O.Speed (X) > 0.0 and then I (O.Center (X)) + O.R >= Pixel_Width - 1) then O.Speed (X) := -O.Speed (X); O.Center (X) := O.Center (X) + O.Speed (X); end if; if (O.Speed (Y) < 0.0 and then I (O.Center (Y)) <= O.R) or else (O.Speed (Y) > 0.0 and then I (O.Center (Y)) + O.R >= Pixel_Height - 1) then O.Speed (Y) := -O.Speed (Y); O.Center (Y) := O.Center (Y) + O.Speed (Y); end if; end loop; for J in Objects'First .. Objects'Last - 1 loop for K in J + 1 .. Objects'Last loop if Collides (Objects (J), Objects (K)) then Handle_Collision (Objects (J), Objects (K)); end if; end loop; end loop; for O of Objects loop Fill_Circle (FG_Buffer, (X => I (O.Center (X)), Y => I (O.Center (Y))), O.R, To_RGB (O.Col)); end loop; Swap_Buffers (Vsync => True); end loop; end Demo;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- The file declares the main procedure for the demonstration. The LEDs -- will blink "in a circle" on the board. The blue user button generates -- an interrupt that changes the direction. with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); -- The "last chance handler" is the user-defined routine that is called when -- an exception is propagated. We need it in the executable, therefore it -- must be somewhere in the closure of the context clauses. with System; with Interfaces; use Interfaces; with STM32.Button; use STM32.Button; with STM32.LCD; use STM32.LCD; with STM32.DMA2D.Interrupt; use STM32.DMA2D; with STM32.RNG.Interrupts; use STM32.RNG.Interrupts; with Bitmapped_Drawing; use Bitmapped_Drawing; with Double_Buffer; use Double_Buffer; procedure Demo is use STM32; pragma Priority (System.Priority'First); type HSV_Color is record Hue : Byte; Sat : Byte; Val : Byte; end record; function To_RGB (Col : HSV_Color) return DMA2D_Color; -- Translates a Hue/Saturation/Value color into RGB type Coordinate is (X, Y); type Vector is array (Coordinate) of Float; function "+" (V1, V2 : Vector) return Vector is begin return (X => V1 (X) + V2 (X), Y => V1 (Y) + V2 (Y)); end "+"; function "-" (V1, V2 : Vector) return Vector is begin return (X => V1 (X) - V2 (X), Y => V1 (Y) - V2 (Y)); end "-"; function "*" (V1, V2 : Vector) return Float is begin return V1 (X) * V2 (X) + V1 (Y) * V2 (Y); end "*"; function "*" (V : Vector; Val : Float) return Vector is begin return (V (X) * Val, V (Y) * Val); end "*"; function "/" (V : Vector; Val : Float) return Vector is begin return (V (X) / Val, V (Y) / Val); end "/"; type Moving_Object is record Center : Vector; Speed : Vector; R : Natural; Col : HSV_Color; N_Hue : Byte; end record; function I (F : Float) return Integer is (Integer (F)); function Collides (M1, M2 : Moving_Object) return Boolean; procedure Handle_Collision (M1, M2 : in out Moving_Object); Objects : array (1 .. 15) of Moving_Object; FG_Buffer : DMA2D_Buffer; White_Background : Boolean := False; ------------ -- To_RGB -- ------------ function To_RGB (Col : HSV_Color) return DMA2D_Color is V, S, H : Word; Region, FPart, p, q, t : Word; Ret : DMA2D_Color; begin Ret.Alpha := 255; if Col.Sat = 0 then Ret.Red := Col.Val; Ret.Green := Col.Val; Ret.Blue := Col.Val; return Ret; end if; V := Word (Col.Val); S := Word (Col.Sat); H := Word (Col.Hue); -- Hue in the range 0 .. 5 Region := H / 43; -- Division reminder, multiplied by 6 to make it in range 0 .. 255 FPart := (H - (Region * 43)) * 6; P := Shift_Right (V * (255 - S), 8); Q := Shift_Right (V * (255 - Shift_Right (S * FPart, 8)), 8); T := Shift_Right (V * (255 - Shift_Right (S * (255 - FPart), 8)), 8); case Region is when 0 => Ret.Red := Byte (V); Ret.Green := Byte (T); Ret.Blue := Byte (P); when 1 => Ret.Red := Byte (Q); Ret.Green := Byte (V); Ret.Blue := Byte (P); when 2 => Ret.Red := Byte (P); Ret.Green := Byte (V); Ret.Blue := Byte (T); when 3 => Ret.Red := Byte (P); Ret.Green := Byte (Q); Ret.Blue := Byte (V); when 4 => Ret.Red := Byte (T); Ret.Green := Byte (P); Ret.Blue := Byte (V); when others => Ret.Red := Byte (V); Ret.Green := Byte (P); Ret.Blue := Byte (Q); end case; return Ret; end To_RGB; ------------- -- Colides -- ------------- function Collides (M1, M2 : Moving_Object) return Boolean is Dist_Min_Square : constant Integer := (M1.R + M2.R) ** 2; M1_M2 : constant Vector := M2.Center - M1.Center; Dist_Square : constant Integer := (I (M1_M2 (X)) ** 2 + I (M1_M2 (Y)) ** 2); begin return Dist_Square < Dist_Min_Square; end Collides; ---------------------- -- Handle_Colisiton -- ---------------------- procedure Handle_Collision (M1, M2 : in out Moving_Object) is -- Dist: distance vector between the two objects Dist : Vector; -- Projx: Projection of the speed of Mx on Dist Tmp : Float; Proj1 : Vector; Proj2 : Vector; Tan_Sp1 : Vector; Tan_Sp2 : Vector; Sp1 : Vector; Sp2 : Vector; -- Simplified mass: equal to R^2 Mass1 : constant Float := Float (M1.R ** 2); Mass2 : constant Float := Float (M2.R ** 2); dT : Float := 0.0; Old1, Old2 : Vector; begin -- Move back before collision -- If we don't, then the balls might still be touching themselves -- after we execute this procedure, so collision is called a second -- time afterwards. Old1 := M1.Center; Old2 := M2.Center; loop dT := dT + 0.2; M1.Center := Old1 - M1.Speed * dT; M2.Center := Old2 - M2.Speed * dT; exit when not Collides (M1, M2); end loop; Dist := (M2.Center - M1.Center); -- Calculate the projection vector of the speeds on Dist Tmp := (M1.Speed * Dist) / (Dist * Dist); Proj1 := Dist * Tmp; Tmp := (M2.Speed * Dist) / (Dist * Dist); Proj2 := Dist * Tmp; -- Now retrieve the speed that is tangantial to dist Tan_Sp1 := M1.Speed - Proj1; Tan_Sp2 := M2.Speed - Proj2; -- Transfer the projected speed from one object to the other Sp1 := (Proj1 * (Mass1 - Mass2) + Proj2 * 2.0 * Mass2) / (Mass1 + Mass2); Sp2 := (Proj2 * (Mass2 - Mass1) + Proj1 * 2.0 * Mass1) / (Mass1 + Mass2); -- Calculate the final speed of the objects: -- initial tangantial speed + calculated projected speed M1.Speed := Sp1 + Tan_Sp1; M2.Speed := Sp2 + Tan_Sp2; -- Now replay from the time of the impact with the new speed M1.Center := M1.Center + M1.Speed * dT; M2.Center := M2.Center + M2.Speed * dT; M1.N_Hue := M1.N_Hue + 32; M2.N_Hue := M2.N_Hue + 32; end Handle_Collision; ---------------- -- Init_Balls -- ---------------- procedure Init_Balls is Size : constant Integer := Natural'Min (Pixel_Width, Pixel_Height); R_Min : constant Natural := Size / 24; R_Var : constant Word := Word (R_Min) * 4 / 5; SP_Max : constant Integer := Size / 7; begin for J in Objects'Range loop loop declare O : Moving_Object renames Objects (J); R : constant Integer := Integer (RNG.Interrupts.Random mod R_Var) + R_Min; Col : constant Byte := Byte (RNG.Interrupts.Random mod 255); X_Raw : constant Word := (RNG.Interrupts.Random mod Word (Pixel_Width - 2 * R)) + Word (R); Y_Raw : constant Word := (RNG.Interrupts.Random mod Word (Pixel_Height - 2 * R)) + Word (R); Sp_X : constant Integer := Integer (RNG.Interrupts.Random mod Word (SP_Max * 2 + 1)) - SP_Max; Sp_Y : constant Integer := Integer (RNG.Interrupts.Random mod Word (SP_Max * 2 + 1)) - SP_Max; Redo : Boolean := False; begin O := (Center => (Float (Natural (X_Raw) + R), Float (Natural (Y_Raw) + R)), Speed => (Float (Sp_X) / 10.0, Float (Sp_Y) / 10.0), R => R, Col => (Hue => Col, Sat => 255, Val => 255), N_Hue => Col); for K in Objects'First .. J - 1 loop if Collides (O, Objects (K)) then Redo := True; exit; end if; end loop; exit when not Redo; end; end loop; end loop; end Init_Balls; begin STM32.LCD.Initialize (Pixel_Fmt_ARGB1555); STM32.DMA2D.Interrupt.Initialize; Double_Buffer.Initialize (Layer_Background => Layer_Double_Buffer, Layer_Foreground => Layer_Inactive); STM32.RNG.Interrupts.Initialize_RNG; STM32.Button.Initialize; Init_Balls; loop if STM32.Button.Has_Been_Pressed then White_Background := not White_Background; end if; FG_Buffer := Double_Buffer.Get_Hidden_Buffer (Background); STM32.DMA2D.DMA2D_Fill (FG_Buffer, (if White_Background then DMA2D.White else DMA2D.Black)); for M of Objects loop if M.N_Hue /= M.Col.Hue then M.Col.Hue := M.Col.Hue + 1; end if; end loop; for O of Objects loop O.Center := O.Center + O.Speed; if (O.Speed (X) < 0.0 and then I (O.Center (X)) <= O.R) or else (O.Speed (X) > 0.0 and then I (O.Center (X)) + O.R >= Pixel_Width - 1) then O.Speed (X) := -O.Speed (X); O.Center (X) := O.Center (X) + O.Speed (X); end if; if (O.Speed (Y) < 0.0 and then I (O.Center (Y)) <= O.R) or else (O.Speed (Y) > 0.0 and then I (O.Center (Y)) + O.R >= Pixel_Height - 1) then O.Speed (Y) := -O.Speed (Y); O.Center (Y) := O.Center (Y) + O.Speed (Y); end if; end loop; for J in Objects'First .. Objects'Last - 1 loop for K in J + 1 .. Objects'Last loop if Collides (Objects (J), Objects (K)) then Handle_Collision (Objects (J), Objects (K)); end if; end loop; end loop; for O of Objects loop Fill_Circle (FG_Buffer, (X => I (O.Center (X)), Y => I (O.Center (Y))), O.R, To_RGB (O.Col)); end loop; Swap_Buffers (Vsync => True); end loop; end Demo;
Fix build issues with the 'balls' example.
Fix build issues with the 'balls' example.
Ada
bsd-3-clause
ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
25af84089c7fc4969e22c2ba66371c085f5134ff
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.adb
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.adb
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- Get a printable representation of the email recipients. function Image (Recipients : in AWS.SMTP.Recipients) return String; -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is pragma Unreferenced (Kind); begin if Message.To = null then Message.To := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); begin To (Message.To'Range) := Message.To.all; Free (Message.To); Message.To := To; end; end if; Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in String) is begin Message.Content := To_Unbounded_String (Content); end Set_Body; -- ------------------------------ -- Get a printable representation of the email recipients. -- ------------------------------ function Image (Recipients : in AWS.SMTP.Recipients) return String is Result : Unbounded_String; begin for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; return To_String (Result); end Image; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if Message.To = null then return; end if; if Message.Manager.Enable then Log.Info ("Send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Message.To.all, Subject => To_String (Message.Subject), Message => To_String (Message.Content), Status => Result); if not AWS.SMTP.Is_Ok (Result) then Log.Error ("Cannot send email: {0}", AWS.SMTP.Status_Message (Result)); end if; else Log.Info ("Disable send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To); end Finalize; procedure Initialize (Client : in out AWS_Mail_Manager'Class; Props : in Util.Properties.Manager'Class) is separate; -- ------------------------------ -- Create a SMTP based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost"); Port : constant String := Props.Get (Name => "smtp.port", Default => "25"); Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1"); Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager; begin Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port); Result.Port := Positive'Value (Port); Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true"; Result.Self := Result; Initialize (Result.all, Props); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.AWS_SMTP;
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012, 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 Ada.Unchecked_Deallocation; with AWS.MIME; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- Get a printable representation of the email recipients. function Image (Recipients : in AWS.SMTP.Recipients) return String; -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is pragma Unreferenced (Kind); begin if Message.To = null then Message.To := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); begin To (Message.To'Range) := Message.To.all; Free (Message.To); Message.To := To; end; end if; Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in Unbounded_String; Alternative : in Unbounded_String; Content_Type : in String) is begin if Length (Alternative) = 0 then AWS.Attachments.Add (Message.Attachments, "", AWS.Attachments.Value (Content)); else AWS.Attachments.Add (Message.Attachments, "", AWS.Attachments.Value (Content, Content_Type => Content_Type)); end if; end Set_Body; -- ------------------------------ -- Add an attachment with the given content. -- ------------------------------ overriding procedure Add_Attachment (Message : in out AWS_Mail_Message; Content : in Unbounded_String; Content_Id : in String; Content_Type : in String) is Data : constant AWS.Attachments.Content := AWS.Attachments.Value (Data => Content, Content_Id => Content_Id, Content_Type => Content_Type); begin AWS.Attachments.Add (Attachments => Message.Attachments, Name => Content_Id, Data => Data); end Add_Attachment; -- ------------------------------ -- Get a printable representation of the email recipients. -- ------------------------------ function Image (Recipients : in AWS.SMTP.Recipients) return String is Result : Unbounded_String; begin for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; return To_String (Result); end Image; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if Message.To = null then return; end if; if Message.Manager.Enable then Log.Info ("Send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Message.To.all, Subject => To_String (Message.Subject), Attachments => Message.Attachments, Status => Result); if not AWS.SMTP.Is_Ok (Result) then Log.Error ("Cannot send email: {0}", AWS.SMTP.Status_Message (Result)); end if; else Log.Info ("Disable send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To); end Finalize; procedure Initialize (Client : in out AWS_Mail_Manager'Class; Props : in Util.Properties.Manager'Class) is separate; -- ------------------------------ -- Create a SMTP based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost"); Port : constant String := Props.Get (Name => "smtp.port", Default => "25"); Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1"); Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager; begin Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port); Result.Port := Positive'Value (Port); Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true"; Result.Self := Result; Initialize (Result.all, Props); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.AWS_SMTP;
Implement Add_Attachment, Set_Body and send a mail with attachment
Implement Add_Attachment, Set_Body and send a mail with attachment
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
61e585bd8426ce517fbe1973e1d579306108680b
UNIT_TESTS/alc_001.adb
UNIT_TESTS/alc_001.adb
with Ada.Containers; with Ada.IO_Exceptions; with Ada.Text_IO; with OpenAL.Context.Error; with OpenAL.Context; with OpenAL.List; with Test; procedure alc_001 is package ALC renames OpenAL.Context; package ALC_Error renames OpenAL.Context.Error; package List renames OpenAL.List; Device : ALC.Device_t; No_Device : ALC.Device_t; Context : ALC.Context_t; OK : Boolean; Caught : Boolean; Devices : List.String_Vector_t; use type ALC.Device_t; use type ALC.Context_t; use type ALC_Error.Error_t; procedure Init is begin Device := ALC.Open_Default_Device; pragma Assert (Device /= ALC.Invalid_Device); Context := ALC.Create_Context (Device); pragma Assert (Context /= ALC.Invalid_Context); OK := ALC.Make_Context_Current (Context); pragma Assert (OK); end Init; procedure Finish is begin ALC.Destroy_Context (Context); OK := ALC.Close_Device (Device); pragma Assert (OK); end Finish; begin Test.Initialize ("alc_001"); Init; Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "DEFAULT_DEVICE_SPEC : " & ALC.Get_Default_Device_Specifier); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "DEVICE_SPEC : " & ALC.Get_Device_Specifier (Device)); begin Caught := False; Ada.Text_IO.Put_Line (Test.Output_File, ALC.Get_Device_Specifier (No_Device)); exception when Ada.IO_Exceptions.Device_Error => Caught := True; end; Test.Check_Test (61, "caught device error for device spec with null device", Caught); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "EXTENSIONS : " & ALC.Get_Extensions (Device)); begin Caught := False; Ada.Text_IO.Put_Line (Test.Output_File, ALC.Get_Extensions (No_Device)); exception when Ada.IO_Exceptions.Device_Error => Caught := True; end; Test.Check_Test (62, "caught device error for extensions with null device", Caught); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "DEFAULT_CAPTURE_DEVICE_SPECIFIER : " & ALC.Get_Default_Capture_Device_Specifier); Devices := ALC.Get_Available_Capture_Devices; if List.String_Vectors.Is_Empty (Devices) = False then Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "DEVICE COUNT: " & Ada.Containers.Count_Type'Image (List.String_Vectors.Length (Devices))); declare procedure Process_Element (Device : in String) is begin Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "CAPTURE_DEVICE: " & Device); end Process_Element; begin for Index in List.String_Vectors.First_Index (Devices) .. List.String_Vectors.Last_Index (Devices) loop List.String_Vectors.Query_Element (Devices, Index, Process_Element'Access); end loop; end; end if; Test.Check_Test (63, "handled available capture devices", True); Finish; Test.Finish; end alc_001;
with Ada.Containers; with Ada.IO_Exceptions; with Ada.Text_IO; with OpenAL.Context.Error; with OpenAL.Context; with OpenAL.List; with OpenAL.Types; with Test; procedure alc_001 is package ALC renames OpenAL.Context; package ALC_Error renames OpenAL.Context.Error; package List renames OpenAL.List; Device : ALC.Device_t; No_Device : ALC.Device_t; Context : ALC.Context_t; OK : Boolean; Caught : Boolean; Devices : List.String_Vector_t; use type ALC.Device_t; use type ALC.Context_t; use type ALC_Error.Error_t; procedure Init is begin Device := ALC.Open_Default_Device; pragma Assert (Device /= ALC.Invalid_Device); Context := ALC.Create_Context (Device); pragma Assert (Context /= ALC.Invalid_Context); OK := ALC.Make_Context_Current (Context); pragma Assert (OK); end Init; procedure Finish is begin ALC.Destroy_Context (Context); OK := ALC.Close_Device (Device); pragma Assert (OK); end Finish; begin Test.Initialize ("alc_001"); Init; Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "DEFAULT_DEVICE_SPEC : " & ALC.Get_Default_Device_Specifier); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "DEVICE_SPEC : " & ALC.Get_Device_Specifier (Device)); begin Caught := False; Ada.Text_IO.Put_Line (Test.Output_File, ALC.Get_Device_Specifier (No_Device)); exception when Ada.IO_Exceptions.Device_Error => Caught := True; end; Test.Check_Test (61, "caught device error for device spec with null device", Caught); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "EXTENSIONS : " & ALC.Get_Extensions (Device)); begin Caught := False; Ada.Text_IO.Put_Line (Test.Output_File, ALC.Get_Extensions (No_Device)); exception when Ada.IO_Exceptions.Device_Error => Caught := True; end; Test.Check_Test (62, "caught device error for extensions with null device", Caught); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "DEFAULT_CAPTURE_DEVICE_SPECIFIER : " & ALC.Get_Default_Capture_Device_Specifier); Devices := ALC.Get_Available_Capture_Devices; if List.String_Vectors.Is_Empty (Devices) = False then Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "DEVICE COUNT: " & Ada.Containers.Count_Type'Image (List.String_Vectors.Length (Devices))); declare procedure Process_Element (Device : in String) is begin Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "CAPTURE_DEVICE: " & Device); end Process_Element; begin for Index in List.String_Vectors.First_Index (Devices) .. List.String_Vectors.Last_Index (Devices) loop List.String_Vectors.Query_Element (Devices, Index, Process_Element'Access); end loop; end; end if; Test.Check_Test (63, "handled available capture devices", True); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "MAJOR_VERSION : " & Natural'Image (ALC.Get_Major_Version (Device))); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "MINOR_VERSION : " & Natural'Image (ALC.Get_Minor_Version (Device))); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "FREQUENCY : " & OpenAL.Types.Frequency_t'Image (ALC.Get_Frequency (Device))); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "REFRESH_RATE : " & Natural'Image (ALC.Get_Refresh (Device))); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "MONO_SOURCES : " & Natural'Image (ALC.Get_Mono_Sources (Device))); Ada.Text_IO.Put_Line (File => Test.Output_File, Item => "STEREO_SOURCES : " & Natural'Image (ALC.Get_Stereo_Sources (Device))); Finish; Test.Finish; end alc_001;
Call integer queries
Call integer queries
Ada
isc
io7m/coreland-openal-ada,io7m/coreland-openal-ada
8826bdbf4ba0d85d5973f4b5890aad5614a66eac
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.Commands.Consoles; with Util.Commands.Consoles.Text; with Druss.Gateways; package Druss.Commands is -- Device selector to select all, active or inactive devices. type Device_Selector_Type is (DEVICE_ALL, DEVICE_ACTIVE, DEVICE_INACTIVE); -- The list of fields that are printed on the console. type Field_Type is (F_IP_ADDR, F_BBOX_IP_ADDR, F_WAN_IP, F_ETHERNET, F_INTERNET, F_VOIP, F_HOSTNAME, F_CONNECTION, F_DEVTYPE, F_ACTIVE, F_LINK, F_WIFI, F_WIFI5, F_ACCESS_CONTROL, F_DYNDNS, F_DEVICES, F_UPTIME, F_COUNT, F_BOOL, F_CHANNEL, F_PROTOCOL, F_ENCRYPTION, F_SSID); -- The type of notice that are reported. type Notice_Type is (N_HELP, N_USAGE, N_INFO); -- Make the generic abstract console interface. package Consoles is new Util.Commands.Consoles (Field_Type => Field_Type, Notice_Type => Notice_Type); -- And the text console to write on stdout (a Gtk console could be done someday). package Text_Consoles is new Consoles.Text; type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; Console : Consoles.Console_Access; 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 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); procedure Initialize; -- Enter in the interactive main loop waiting for user commands and executing them. procedure Interactive (Context : in out Context_Type); -- Print the bbox API status. procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a ON/OFF status. procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a uptime. procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a performance measure in us or ms. procedure Print_Perf (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); 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 Util.Commands.Consoles; with Util.Commands.Consoles.Text; with Druss.Gateways; package Druss.Commands is -- Exception raised to stop the interactive loop. Stop_Interactive : exception; -- Device selector to select all, active or inactive devices. type Device_Selector_Type is (DEVICE_ALL, DEVICE_ACTIVE, DEVICE_INACTIVE); -- The list of fields that are printed on the console. type Field_Type is (F_IP_ADDR, F_BBOX_IP_ADDR, F_WAN_IP, F_ETHERNET, F_INTERNET, F_VOIP, F_HOSTNAME, F_CONNECTION, F_DEVTYPE, F_ACTIVE, F_LINK, F_WIFI, F_WIFI5, F_ACCESS_CONTROL, F_DYNDNS, F_DEVICES, F_UPTIME, F_COUNT, F_BOOL, F_CHANNEL, F_PROTOCOL, F_ENCRYPTION, F_SSID); -- The type of notice that are reported. type Notice_Type is (N_HELP, N_USAGE, N_INFO); -- Make the generic abstract console interface. package Consoles is new Util.Commands.Consoles (Field_Type => Field_Type, Notice_Type => Notice_Type); -- And the text console to write on stdout (a Gtk console could be done someday). package Text_Consoles is new Consoles.Text; type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; Console : Consoles.Console_Access; 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 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); procedure Initialize; -- Enter in the interactive main loop waiting for user commands and executing them. procedure Interactive (Context : in out Context_Type); -- Print the bbox API status. procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a ON/OFF status. procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a uptime. procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a performance measure in us or ms. procedure Print_Perf (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); end Druss.Commands;
Declare the Stop_Interactive exception
Declare the Stop_Interactive exception
Ada
apache-2.0
stcarrez/bbox-ada-api
18315a2c0549f39254861b0220d48767bf7561e7
matp/src/symbols/mat-symbols-targets.adb
matp/src/symbols/mat-symbols-targets.adb
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files management -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Bfd.Sections; package body MAT.Symbols.Targets is -- ------------------------------ -- Open the binary and load the symbols from that file. -- ------------------------------ procedure Open (Symbols : in out Target_Symbols; Path : in String) is begin Bfd.Files.Open (Symbols.File, Path, ""); if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); end if; end Open; procedure Open (Symbols : in out Library_Symbols; Path : in String) is begin Bfd.Files.Open (Symbols.File, Path, ""); if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); end if; end Open; -- ------------------------------ -- Load the symbols associated with a shared library described by the memory region. -- ------------------------------ procedure Load_Symbols (Symbols : in out Target_Symbols; Region : in MAT.Memory.Region_Info) is Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr); Syms : Library_Symbols_Ref; begin if not Symbols_Maps.Has_Element (Pos) then Syms := Library_Symbols_Refs.Create; Syms.Value.Start_Addr := Region.Start_Addr; Syms.Value.End_Addr := Region.End_Addr; Symbols.Libraries.Insert (Region.Start_Addr, Syms); else Syms := Symbols_Maps.Element (Pos); end if; Open (Syms.Value.all, Ada.Strings.Unbounded.To_String (Region.Path)); end Load_Symbols; -- ------------------------------ -- Find the nearest source file and line for the given address. -- ------------------------------ procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Name : out Ada.Strings.Unbounded.Unbounded_String; Func : out Ada.Strings.Unbounded.Unbounded_String; Line : out Natural) is Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr); Text_Section : Bfd.Sections.Section; begin Line := 0; if Symbols_Maps.Has_Element (Pos) then declare Syms : Library_Symbols_Ref := Symbols_Maps.Element (Pos); Offset : constant Bfd.Vma_Type := Bfd.Vma_Type (Addr - Syms.Value.Start_Addr); begin if Syms.Value.End_Addr > Addr then if Bfd.Files.Is_Open (Syms.Value.File) then Text_Section := Bfd.Sections.Find_Section (Syms.Value.File, ".text"); Bfd.Symbols.Find_Nearest_Line (File => Syms.Value.File, Sec => Text_Section, Symbols => Syms.Value.Symbols, Addr => Offset, Name => Name, Func => Func, Line => Line); return; end if; end if; end; end if; if Bfd.Files.Is_Open (Symbols.File) then Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text"); Bfd.Symbols.Find_Nearest_Line (File => Symbols.File, Sec => Text_Section, Symbols => Symbols.Symbols, Addr => Bfd.Vma_Type (Addr), Name => Name, Func => Func, Line => Line); else Line := 0; Name := Ada.Strings.Unbounded.To_Unbounded_String (""); Func := Ada.Strings.Unbounded.To_Unbounded_String (""); end if; exception when Bfd.NOT_FOUND => Line := 0; Name := Ada.Strings.Unbounded.To_Unbounded_String (""); Func := Ada.Strings.Unbounded.To_Unbounded_String (""); end Find_Nearest_Line; end MAT.Symbols.Targets;
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files 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 Bfd.Sections; with Util.Log.Loggers; package body MAT.Symbols.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Symbols.Targets"); -- ------------------------------ -- Open the binary and load the symbols from that file. -- ------------------------------ procedure Open (Symbols : in out Target_Symbols; Path : in String) is begin Log.Info ("Loading symbols from {0}", Path); Bfd.Files.Open (Symbols.File, Path, ""); if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); end if; end Open; procedure Open (Symbols : in out Region_Symbols; Path : in String) is begin Log.Info ("Loading symbols from {0}", Path); Bfd.Files.Open (Symbols.File, Path, ""); if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); end if; end Open; -- ------------------------------ -- Load the symbols associated with a shared library described by the memory region. -- ------------------------------ procedure Load_Symbols (Symbols : in out Target_Symbols; Region : in MAT.Memory.Region_Info; Offset_Addr : in MAT.Types.Target_Addr) is Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr); Syms : Region_Symbols_Ref; begin if not Symbols_Maps.Has_Element (Pos) then Syms := Region_Symbols_Refs.Create; Syms.Value.Region := Region; Syms.Value.Offset := Offset_Addr; Symbols.Libraries.Insert (Region.Start_Addr, Syms); else Syms := Symbols_Maps.Element (Pos); end if; if Ada.Strings.Unbounded.Length (Region.Path) > 0 then Open (Syms.Value.all, Ada.Strings.Unbounded.To_String (Region.Path)); end if; end Load_Symbols; procedure Find_Nearest_Line (Symbols : in Region_Symbols; Addr : in MAT.Types.Target_Addr; Name : out Ada.Strings.Unbounded.Unbounded_String; Func : out Ada.Strings.Unbounded.Unbounded_String; Line : out Natural) is use type Bfd.Vma_Type; Text_Section : Bfd.Sections.Section; Pc : Bfd.Vma_Type := Bfd.Vma_Type (Addr); begin if not Bfd.Files.Is_Open (Symbols.File) then Func := Symbols.Region.Path; return; end if; Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text"); -- if Text_Section.Vma > Pc or else Text_Section.Vma + Text_Section.Size < Pc then -- -- end if; Bfd.Symbols.Find_Nearest_Line (File => Symbols.File, Sec => Text_Section, Symbols => Symbols.Symbols, Addr => Pc, Name => Name, Func => Func, Line => Line); end Find_Nearest_Line; -- ------------------------------ -- Find the nearest source file and line for the given address. -- ------------------------------ procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Name : out Ada.Strings.Unbounded.Unbounded_String; Func : out Ada.Strings.Unbounded.Unbounded_String; Line : out Natural) is Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr); Text_Section : Bfd.Sections.Section; begin Line := 0; if Symbols_Maps.Has_Element (Pos) then declare Syms : Region_Symbols_Ref := Symbols_Maps.Element (Pos); begin if Syms.Value.Region.End_Addr > Addr then Find_Nearest_Line (Symbols => Syms.Value.all, Addr => Addr - Syms.Value.Offset, Name => Name, Func => Func, Line => Line); return; end if; end; end if; if Bfd.Files.Is_Open (Symbols.File) then Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text"); Bfd.Symbols.Find_Nearest_Line (File => Symbols.File, Sec => Text_Section, Symbols => Symbols.Symbols, Addr => Bfd.Vma_Type (Addr), Name => Name, Func => Func, Line => Line); else Line := 0; Name := Ada.Strings.Unbounded.To_Unbounded_String (""); Func := Ada.Strings.Unbounded.To_Unbounded_String (""); end if; exception when Bfd.NOT_FOUND => Line := 0; Name := Ada.Strings.Unbounded.To_Unbounded_String (""); Func := Ada.Strings.Unbounded.To_Unbounded_String (""); end Find_Nearest_Line; end MAT.Symbols.Targets;
Update the Load_Symbols and Find_Nearest_Line to search for the main symbol or a library symbol
Update the Load_Symbols and Find_Nearest_Line to search for the main symbol or a library symbol
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c10fa52cc064c90bc3b5981bf834ed3480b64385
awa/src/awa-events.ads
awa/src/awa-events.ads
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Objects.Maps; with ADO; with AWA.Index_Arrays; -- == Introduction == -- The <b>AWA.Events</b> package defines an event framework for modules to post events -- and have Ada bean methods be invoked when these events are dispatched. Subscription to -- events is done through configuration files. This allows to configure the modules and -- integrate them together easily at configuration time. -- -- === Declaration === -- Modules define the events that they can generate by instantiating the <b>Definition</b> -- package. This is a static definition of the event. Each event is given a unique name. -- -- package Event_New_User is new AWA.Events.Definition ("new-user"); -- -- === Posting an event === -- The module can post an event to inform other modules or the system that a particular -- action occurred. The module creates the event instance of type <b>Module_Event</b> and -- populates that event with useful properties for event receivers. -- -- Event : AWA.Events.Module_Event; -- -- Event.Set_Event_Kind (Event_New_User.Kind); -- Event.Set_Parameter ("email", "[email protected]"); -- -- The module will post the event by using the <b>Send_Event</b> operation. -- -- Manager.Send_Event (Event); -- -- === Receiving an event === -- Modules or applications interested by a particular event will configure the event manager -- to dispatch the event to an Ada bean event action. The Ada bean is an object that must -- implement a procedure that matches the prototype: -- -- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...; -- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); -- -- The Ada bean method and object are registered as other Ada beans. -- -- The configuration file indicates how to bind the Ada bean action and the event together. -- The action is specified using an EL Method Expression (See Ada EL or JSR 245). -- -- <on-event name="new_user"> -- <action>#{ada_bean.action}</action> -- </on-event> -- -- === Event queues and dispatchers === -- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them. -- There are two kinds of dispatchers: -- -- * Synchronous dispatcher process the event when it is posted. The task which posts -- the event invokes the Ada bean action. In this dispatching mode, there is no event queue. -- If the action method raises an exception, it will however be blocked. -- -- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event -- queue. A dispatcher task processes the event and invokes the action method at a later -- time. -- -- When the event is queued, there are two types of event queues: -- -- * A Fifo memory queue manages the event and dispatches them in FIFO order. -- If the application is stopped, the events present in the Fifo queue are lost. -- -- * A persistent event queue manages the event in a similar way as the FIFO queue but -- saves them in the database. If the application is stopped, events that have not yet -- been processed will be dispatched when the application is started again. -- -- == Data Model == -- @include Queues.hbm.xml -- package AWA.Events is type Queue_Index is new Natural; type Event_Index is new Natural; package Event_Arrays is new AWA.Index_Arrays (Event_Index); generic package Definition renames Event_Arrays.Definition; -- Exception raised if an event name is not found. Not_Found : exception renames Event_Arrays.Not_Found; -- Identifies an invalid event. -- Invalid_Event : constant Event_Index := 0; -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. function Find_Event_Index (Name : in String) return Event_Index renames Event_Arrays.Find; -- ------------------------------ -- Module event -- ------------------------------ type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private; type Module_Event_Access is access all Module_Event'Class; -- Set the event type which identifies the event. procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index); -- Get the event type which identifies the event. function Get_Event_Kind (Event : in Module_Event) return Event_Index; -- Set a parameter on the message. procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String); -- Get the parameter with the given name. function Get_Parameter (Event : in Module_Event; Name : in String) return String; -- Get the value that corresponds to the parameter with the given name. overriding function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object; -- Get the entity identifier associated with the event. function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier; -- Set the entity identifier associated with the event. procedure Set_Entity_Identifier (Event : in out Module_Event; Id : in ADO.Identifier); -- Copy the event properties to the map passed in <tt>Into</tt>. procedure Copy (Event : in Module_Event; Into : in out Util.Beans.Objects.Maps.Map); private type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record Kind : Event_Index := Event_Arrays.Invalid_Index; Props : Util.Beans.Objects.Maps.Map; Entity : ADO.Identifier := ADO.NO_IDENTIFIER; Entity_Type : ADO.Entity_Type := ADO.NO_ENTITY_TYPE; end record; -- The index of the last event definition. -- Last_Event : Event_Index := 0; -- Get the event type name. function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access renames Event_Arrays.Get_Name; -- Make and return a copy of the event. function Copy (Event : in Module_Event) return Module_Event_Access; end AWA.Events;
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Objects.Maps; with ADO; with AWA.Index_Arrays; -- == Introduction == -- The <b>AWA.Events</b> package defines an event framework for modules to post events -- and have Ada bean methods be invoked when these events are dispatched. Subscription to -- events is done through configuration files. This allows to configure the modules and -- integrate them together easily at configuration time. -- -- === Declaration === -- Modules define the events that they can generate by instantiating the <b>Definition</b> -- package. This is a static definition of the event. Each event is given a unique name. -- -- package Event_New_User is new AWA.Events.Definition ("new-user"); -- -- === Posting an event === -- The module can post an event to inform other modules or the system that a particular -- action occurred. The module creates the event instance of type <b>Module_Event</b> and -- populates that event with useful properties for event receivers. -- -- Event : AWA.Events.Module_Event; -- -- Event.Set_Event_Kind (Event_New_User.Kind); -- Event.Set_Parameter ("email", "[email protected]"); -- -- The module will post the event by using the <b>Send_Event</b> operation. -- -- Manager.Send_Event (Event); -- -- === Receiving an event === -- Modules or applications interested by a particular event will configure the event manager -- to dispatch the event to an Ada bean event action. The Ada bean is an object that must -- implement a procedure that matches the prototype: -- -- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...; -- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); -- -- The Ada bean method and object are registered as other Ada beans. -- -- The configuration file indicates how to bind the Ada bean action and the event together. -- The action is specified using an EL Method Expression (See Ada EL or JSR 245). -- -- <on-event name="new_user"> -- <action>#{ada_bean.action}</action> -- </on-event> -- -- === Event queues and dispatchers === -- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them. -- There are two kinds of dispatchers: -- -- * Synchronous dispatcher process the event when it is posted. The task which posts -- the event invokes the Ada bean action. In this dispatching mode, there is no event queue. -- If the action method raises an exception, it will however be blocked. -- -- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event -- queue. A dispatcher task processes the event and invokes the action method at a later -- time. -- -- When the event is queued, there are two types of event queues: -- -- * A Fifo memory queue manages the event and dispatches them in FIFO order. -- If the application is stopped, the events present in the Fifo queue are lost. -- -- * A persistent event queue manages the event in a similar way as the FIFO queue but -- saves them in the database. If the application is stopped, events that have not yet -- been processed will be dispatched when the application is started again. -- -- == Data Model == -- @include Queues.hbm.xml -- package AWA.Events is type Queue_Index is new Natural; type Event_Index is new Natural; package Event_Arrays is new AWA.Index_Arrays (Event_Index, String); use type Event_Arrays.Element_Type_Access; subtype Name_Access is Event_Arrays.Element_Type_Access; generic package Definition renames Event_Arrays.Definition; -- Exception raised if an event name is not found. Not_Found : exception renames Event_Arrays.Not_Found; -- Identifies an invalid event. -- Invalid_Event : constant Event_Index := 0; -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. function Find_Event_Index (Name : in String) return Event_Index renames Event_Arrays.Find; -- ------------------------------ -- Module event -- ------------------------------ type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private; type Module_Event_Access is access all Module_Event'Class; -- Set the event type which identifies the event. procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index); -- Get the event type which identifies the event. function Get_Event_Kind (Event : in Module_Event) return Event_Index; -- Set a parameter on the message. procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String); -- Get the parameter with the given name. function Get_Parameter (Event : in Module_Event; Name : in String) return String; -- Get the value that corresponds to the parameter with the given name. overriding function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object; -- Get the entity identifier associated with the event. function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier; -- Set the entity identifier associated with the event. procedure Set_Entity_Identifier (Event : in out Module_Event; Id : in ADO.Identifier); -- Copy the event properties to the map passed in <tt>Into</tt>. procedure Copy (Event : in Module_Event; Into : in out Util.Beans.Objects.Maps.Map); private type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record Kind : Event_Index := Event_Arrays.Invalid_Index; Props : Util.Beans.Objects.Maps.Map; Entity : ADO.Identifier := ADO.NO_IDENTIFIER; Entity_Type : ADO.Entity_Type := ADO.NO_ENTITY_TYPE; end record; -- The index of the last event definition. -- Last_Event : Event_Index := 0; -- Get the event type name. function Get_Event_Type_Name (Index : in Event_Index) return Name_Access renames Event_Arrays.Get_Element; -- Make and return a copy of the event. function Copy (Event : in Module_Event) return Module_Event_Access; end AWA.Events;
Update the Event_Arrays instantiation to indicate that each event definition is represented by a String
Update the Event_Arrays instantiation to indicate that each event definition is represented by a String
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d72d3b33eb9763d9d8015016d96469b9c4814012
src/ado-drivers-connections.ads
src/ado-drivers-connections.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; with Util.Strings; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers.Connections is use ADO.Statements; type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Ada.Finalization.Limited_Controlled with record Count : Natural := 0; Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Get the database driver which manages this connection. function Get_Driver (Database : in Database_Connection) return Driver_Access is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Controller : in out Configuration; URI : in String); -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Controller : in Configuration; Name : in String) return String; -- Set the server hostname. procedure Set_Server (Controller : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Controller : in Configuration) return String; -- Set the server port. procedure Set_Port (Controller : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Controller : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Controller : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Controller : in Configuration) return String; -- Get the database driver name. function Get_Driver (Controller : in Configuration) return String; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access); -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : out Database_Connection_Access) is abstract; -- Get the driver unique index. function Get_Driver_Index (D : in Driver) return Driver_Index; -- Get the driver name. function Get_Driver_Name (D : in Driver) return String; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Util.Strings.Name_Access; Index : Driver_Index; end record; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String := Null_Unbounded_String; Server : Unbounded_String := Null_Unbounded_String; Port : Natural := 0; Database : Unbounded_String := Null_Unbounded_String; Properties : Util.Properties.Manager; Driver : Driver_Access; end record; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; with Util.Strings; with Util.Refs; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers.Connections is use ADO.Statements; type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Util.Refs.Ref_Entity with record Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Get the database driver which manages this connection. function Get_Driver (Database : in Database_Connection) return Driver_Access is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; package Ref is new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class, Element_Access => Database_Connection_Access); -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Controller : in out Configuration; URI : in String); -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Controller : in Configuration; Name : in String) return String; -- Set the server hostname. procedure Set_Server (Controller : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Controller : in Configuration) return String; -- Set the server port. procedure Set_Port (Controller : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Controller : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Controller : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Controller : in Configuration) return String; -- Get the database driver name. function Get_Driver (Controller : in Configuration) return String; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is abstract; -- Get the driver unique index. function Get_Driver_Index (D : in Driver) return Driver_Index; -- Get the driver name. function Get_Driver_Name (D : in Driver) return String; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Util.Strings.Name_Access; Index : Driver_Index; end record; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String := Null_Unbounded_String; Server : Unbounded_String := Null_Unbounded_String; Port : Natural := 0; Database : Unbounded_String := Null_Unbounded_String; Properties : Util.Properties.Manager; Driver : Driver_Access; end record; end ADO.Drivers.Connections;
Change the implementation to use the Util.Refs generic package for reference counting Update the driver API accordingly
Change the implementation to use the Util.Refs generic package for reference counting Update the driver API accordingly
Ada
apache-2.0
stcarrez/ada-ado
ecab701286ea14dcfdcfd6d1892ddaefec19b729
src/http/util-mail.adb
src/http/util-mail.adb
----------------------------------------------------------------------- -- util-mail -- Mail Utility Library -- 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.Fixed; package body Util.Mail is use Ada.Strings.Unbounded; use Ada.Strings.Fixed; use Ada.Strings; -- ------------------------------ -- Parse the email address and separate the name from the address. -- ------------------------------ function Parse_Address (E_Mail : in String) return Email_Address is Result : Email_Address; First_Pos : constant Natural := Index (E_Mail, "<"); Last_Pos : constant Natural := Index (E_Mail, ">"); At_Pos : constant Natural := Index (E_Mail, "@"); begin if First_Pos > 0 and Last_Pos > 0 then Result.Name := To_Unbounded_String (Trim (E_Mail (E_Mail'First .. First_Pos - 1), Both)); Result.Address := To_Unbounded_String (Trim (E_Mail (First_Pos + 1 .. Last_Pos - 1), Both)); if Length (Result.Name) = 0 and At_Pos < Last_Pos then Result.Name := To_Unbounded_String (Trim (E_Mail (First_Pos + 1 .. At_Pos - 1), Both)); end if; else Result.Address := To_Unbounded_String (Trim (E_Mail, Both)); Result.Name := To_Unbounded_String (Trim (E_Mail (E_Mail'First .. At_Pos - 1), Both)); end if; return Result; end Parse_Address; -- ------------------------------ -- Extract a first name from the email address. -- ------------------------------ function Get_First_Name (From : in Email_Address) return String is Name : constant String := To_String (From.Name); Pos : Natural := Index (Name, " "); begin if Pos > 0 then return Name (Name'First .. Pos - 1); end if; Pos := Index (Name, "."); if Pos > 0 then return Name (Name'First .. Pos - 1); else return ""; end if; end Get_First_Name; end Util.Mail;
----------------------------------------------------------------------- -- util-mail -- Mail Utility Library -- 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.Fixed; package body Util.Mail is use Ada.Strings.Unbounded; use Ada.Strings.Fixed; use Ada.Strings; -- ------------------------------ -- Parse the email address and separate the name from the address. -- ------------------------------ function Parse_Address (E_Mail : in String) return Email_Address is Result : Email_Address; First_Pos : constant Natural := Index (E_Mail, "<"); Last_Pos : constant Natural := Index (E_Mail, ">"); At_Pos : constant Natural := Index (E_Mail, "@"); begin if First_Pos > 0 and Last_Pos > 0 then Result.Name := To_Unbounded_String (Trim (E_Mail (E_Mail'First .. First_Pos - 1), Both)); Result.Address := To_Unbounded_String (Trim (E_Mail (First_Pos + 1 .. Last_Pos - 1), Both)); if Length (Result.Name) = 0 and At_Pos < Last_Pos then Result.Name := To_Unbounded_String (Trim (E_Mail (First_Pos + 1 .. At_Pos - 1), Both)); end if; else Result.Address := To_Unbounded_String (Trim (E_Mail, Both)); Result.Name := To_Unbounded_String (Trim (E_Mail (E_Mail'First .. At_Pos - 1), Both)); end if; return Result; end Parse_Address; -- ------------------------------ -- Extract a first name from the email address. -- ------------------------------ function Get_First_Name (From : in Email_Address) return String is Name : constant String := To_String (From.Name); Pos : Natural := Index (Name, " "); begin if Pos > 0 then return Name (Name'First .. Pos - 1); end if; Pos := Index (Name, "."); if Pos > 0 then return Name (Name'First .. Pos - 1); else return ""; end if; end Get_First_Name; -- ------------------------------ -- Extract a last name from the email address. -- ------------------------------ function Get_Last_Name (From : in Email_Address) return String is Name : constant String := To_String (From.Name); Pos : Natural := Index (Name, " "); begin if Pos > 0 then return Trim (Name (Pos + 1 .. Name'Last), Both); end if; Pos := Index (Name, "."); if Pos > 0 then return Name (Pos + 1 .. Name'Last); else return Name; end if; end Get_Last_Name; end Util.Mail;
Implement the Get_Last_Name function to extract a possible last name for the user
Implement the Get_Last_Name function to extract a possible last name for the user
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
fe20411c9f28eaa3238a7f2ceb49b86200004093
src/wiki-utils.adb
src/wiki-utils.adb
----------------------------------------------------------------------- -- wiki-utils -- Wiki utility operations -- 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 Wiki.Render.Text; with Wiki.Render.Html; with Wiki.Filters.Html; with Wiki.Writers.Builders; package body Wiki.Utils is -- ------------------------------ -- Render the wiki text according to the wiki syntax in HTML into a string. -- ------------------------------ function To_Html (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Writer : aliased Wiki.Writers.Builders.Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; begin Renderer.Set_Writer (Writer'Unchecked_Access); Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Filter'Unchecked_Access, Text, Syntax); return Writer.To_String; end To_Html; -- ------------------------------ -- Render the wiki text according to the wiki syntax in text into a string. -- Wiki formatting and decoration are removed. -- ------------------------------ function To_Text (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access); Wiki.Parsers.Parse (Renderer'Unchecked_Access, Text, Syntax); return Writer.To_String; end To_Text; end Wiki.Utils;
----------------------------------------------------------------------- -- wiki-utils -- Wiki utility operations -- 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 Wiki.Render.Text; with Wiki.Render.Html; with Wiki.Filters.Html; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; package body Wiki.Utils is -- ------------------------------ -- Render the wiki text according to the wiki syntax in HTML into a string. -- ------------------------------ function To_Html (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Stream'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Text, Renderer'Unchecked_Access); return Stream.To_String; end To_Html; -- ------------------------------ -- Render the wiki text according to the wiki syntax in text into a string. -- Wiki formatting and decoration are removed. -- ------------------------------ function To_Text (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Stream'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Text, Renderer'Unchecked_Access); return Stream.To_String; end To_Text; end Wiki.Utils;
Update the To_Html and To_Text function to use the new wiki engine implementation
Update the To_Html and To_Text function to use the new wiki engine implementation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
74816706bdf72c1c44fe655232dbf4ee092a5827
mat/src/mat-readers-streams.ads
mat/src/mat-readers-streams.ads
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- 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.Streams.Buffered; package MAT.Readers.Streams is type Stream_Reader_Type is new Manager_Base with private; -- Read the events from the stream and stop when the end of the stream is reached. procedure Read_All (Reader : in out Stream_Reader_Type); -- Read a message from the stream. overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message); private type Stream_Reader_Type is new Manager_Base with record Stream : Util.Streams.Buffered.Buffered_Stream; Data : Util.Streams.Buffered.Buffer_Access; end record; end MAT.Readers.Streams;
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- 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.Streams.Buffered; with MAT.Events.Probes; with MAT.Events.Targets; package MAT.Readers.Streams is type Stream_Reader_Type is new MAT.Events.Probes.Probe_Manager_Type with private; -- Read the events from the stream and stop when the end of the stream is reached. procedure Read_All (Reader : in out Stream_Reader_Type); -- Read a message from the stream. overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message_Type); private type Stream_Reader_Type is new MAT.Events.Probes.Probe_Manager_Type with record Stream : Util.Streams.Buffered.Buffered_Stream; Data : Util.Streams.Buffered.Buffer_Access; end record; end MAT.Readers.Streams;
Use the Message_Type and MAT.Events.Probes.Probe_Manager_Type types
Use the Message_Type and MAT.Events.Probes.Probe_Manager_Type types
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
60728cda99067e9406b57ae9aeb1f5fb7350163c
regtests/asf-applications-main-tests.adb
regtests/asf-applications-main-tests.adb
----------------------------------------------------------------------- -- asf-applications-main-tests - Unit tests for Applications -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Objects; with Ada.Unchecked_Deallocation; with EL.Contexts.Default; with ASF.Applications.Tests; with ASF.Applications.Main.Configs; with ASF.Requests.Mockup; package body ASF.Applications.Main.Tests is use Util.Tests; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access; package Caller is new Util.Test_Caller (Test, "Applications.Main"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Applications.Main.Read_Configuration", Test_Read_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create", Test_Create_Bean'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Load_Bundle", Test_Load_Bundle'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Register,Load_Bundle", Test_Bundle_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Get_Supported_Locales", Test_Locales'Access); end Add_Tests; -- ------------------------------ -- Initialize the test application -- ------------------------------ procedure Set_Up (T : in out Test) is Fact : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; begin T.App := new ASF.Applications.Main.Application; C.Copy (Util.Tests.Get_Properties); T.App.Initialize (C, Fact); T.App.Register ("layoutMsg", "layout"); end Set_Up; -- ------------------------------ -- Deletes the application object -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class, Name => ASF.Applications.Main.Application_Access); begin Free (T.App); end Tear_Down; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Applications.Tests.Form_Bean_Access := new Applications.Tests.Form_Bean; begin return Result.all'Access; end Create_Form_Bean; -- ------------------------------ -- Test creation of module -- ------------------------------ procedure Test_Read_Configuration (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("config/empty.xml"); begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); end Test_Read_Configuration; -- ------------------------------ -- Test creation of a module and registration in an application. -- ------------------------------ procedure Test_Create_Bean (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type); procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type) is Value : Util.Beans.Objects.Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Context : EL.Contexts.Default.Default_Context; begin T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Context => Context, Result => Bean, Scope => Scope); T.Assert (Kind = Scope, "Invalid scope for " & Name); T.Assert (Bean /= null, "Invalid bean object"); Value := Util.Beans.Objects.To_Object (Bean); T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean"); -- Special test for the sessionForm bean which is initialized by configuration properties if Name = "sessionForm" then T.Assert_Equals ("[email protected]", Util.Beans.Objects.To_String (Bean.Get_Value ("email")), "Session form not initialized"); end if; end Check; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-module.xml"); begin T.App.Register_Class ("ASF.Applications.Tests.Form_Bean", Create_Form_Bean'Access); ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); -- Check the 'regtests/config/test-module.xml' managed bean configuration. Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE); Check ("sessionForm", ASF.Beans.SESSION_SCOPE); Check ("requestForm", ASF.Beans.REQUEST_SCOPE); end Test_Create_Bean; -- ------------------------------ -- Test loading a resource bundle through the application. -- ------------------------------ procedure Test_Load_Bundle (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml"); Bundle : ASF.Locales.Bundle; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Load_Bundle (Name => "samples", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Equals (T, "Help", String '(Bundle.Get ("layout_help_label")), "Invalid bundle value"); T.App.Load_Bundle (Name => "asf", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Matches (T, ".*greater than.*", String '(Bundle.Get ("validators.length.maximum")), "Invalid bundle value"); end Test_Load_Bundle; -- ------------------------------ -- Test application configuration and registration of resource bundles. -- ------------------------------ procedure Test_Bundle_Configuration (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml"); Result : Util.Beans.Basic.Readonly_Bean_Access; Ctx : EL.Contexts.Default.Default_Context; Scope : Scope_Type; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("samplesMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The samplesMsg bundle was not created"); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("defaultMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The defaultMsg bundle was not created"); end Test_Bundle_Configuration; -- ------------------------------ -- Test locales. -- ------------------------------ procedure Test_Locales (T : in out Test) is use Util.Locales; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-locales.xml"); Req : aliased ASF.Requests.Mockup.Request; View : constant access Applications.Views.View_Handler'Class := T.App.Get_View_Handler; Context : aliased ASF.Contexts.Faces.Faces_Context; ELContext : aliased EL.Contexts.Default.Default_Context; Locale : Util.Locales.Locale; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (T.App.Get_Default_Locale), "Invalid default locale"); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Request (Req'Unchecked_Access); Req.Set_Header ("Accept-Language", "da, en-gb;q=0.3, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, en-gb, en;q=0.8, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.ENGLISH), To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, ru, it;q=0.8, de;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); end Test_Locales; end ASF.Applications.Main.Tests;
----------------------------------------------------------------------- -- asf-applications-main-tests - Unit tests for Applications -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Objects; with Ada.Unchecked_Deallocation; with EL.Contexts.Default; with ASF.Applications.Tests; with ASF.Applications.Main.Configs; with ASF.Requests.Mockup; package body ASF.Applications.Main.Tests is use Util.Tests; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access; package Caller is new Util.Test_Caller (Test, "Applications.Main"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Applications.Main.Read_Configuration", Test_Read_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create", Test_Create_Bean'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Load_Bundle", Test_Load_Bundle'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Register,Load_Bundle", Test_Bundle_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Get_Supported_Locales", Test_Locales'Access); end Add_Tests; -- ------------------------------ -- Initialize the test application -- ------------------------------ procedure Set_Up (T : in out Test) is Fact : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; begin T.App := new ASF.Applications.Main.Application; C.Copy (Util.Tests.Get_Properties); T.App.Initialize (C, Fact); T.App.Register ("layoutMsg", "layout"); end Set_Up; -- ------------------------------ -- Deletes the application object -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class, Name => ASF.Applications.Main.Application_Access); begin Free (T.App); end Tear_Down; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Applications.Tests.Form_Bean_Access := new Applications.Tests.Form_Bean; begin return Result.all'Access; end Create_Form_Bean; -- ------------------------------ -- Test creation of module -- ------------------------------ procedure Test_Read_Configuration (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("config/empty.xml"); begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); end Test_Read_Configuration; -- ------------------------------ -- Test creation of a module and registration in an application. -- ------------------------------ procedure Test_Create_Bean (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type); procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type) is Value : Util.Beans.Objects.Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Context : EL.Contexts.Default.Default_Context; begin T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Context => Context, Result => Bean, Scope => Scope); T.Assert (Kind = Scope, "Invalid scope for " & Name); T.Assert (Bean /= null, "Invalid bean object"); Value := Util.Beans.Objects.To_Object (Bean); T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean"); -- Special test for the sessionForm bean which is initialized by configuration properties if Name = "sessionForm" then T.Assert_Equals ("[email protected]", Util.Beans.Objects.To_String (Bean.Get_Value ("email")), "Session form not initialized"); end if; end Check; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-module.xml"); begin T.App.Register_Class ("ASF.Applications.Tests.Form_Bean", Create_Form_Bean'Access); ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); -- Check the 'regtests/config/test-module.xml' managed bean configuration. Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE); Check ("sessionForm", ASF.Beans.SESSION_SCOPE); Check ("requestForm", ASF.Beans.REQUEST_SCOPE); end Test_Create_Bean; -- ------------------------------ -- Test loading a resource bundle through the application. -- ------------------------------ procedure Test_Load_Bundle (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml"); Bundle : ASF.Locales.Bundle; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Load_Bundle (Name => "samples", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Equals (T, "Help", String '(Bundle.Get ("layout_help_label")), "Invalid bundle value"); T.App.Load_Bundle (Name => "asf", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Matches (T, ".*greater than.*", String '(Bundle.Get ("validators.length.maximum")), "Invalid bundle value"); end Test_Load_Bundle; -- ------------------------------ -- Test application configuration and registration of resource bundles. -- ------------------------------ procedure Test_Bundle_Configuration (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml"); Result : Util.Beans.Basic.Readonly_Bean_Access; Ctx : EL.Contexts.Default.Default_Context; Scope : Scope_Type; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("samplesMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The samplesMsg bundle was not created"); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("defaultMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The defaultMsg bundle was not created"); end Test_Bundle_Configuration; -- ------------------------------ -- Test locales. -- ------------------------------ procedure Test_Locales (T : in out Test) is use Util.Locales; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-locales.xml"); Req : aliased ASF.Requests.Mockup.Request; View : constant access Applications.Views.View_Handler'Class := T.App.Get_View_Handler; Context : aliased ASF.Contexts.Faces.Faces_Context; ELContext : aliased EL.Contexts.Default.Default_Context; Locale : Util.Locales.Locale; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (T.App.Get_Default_Locale), "Invalid default locale"); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Request (Req'Unchecked_Access); Req.Set_Header ("Accept-Language", "da, en-gb;q=0.3, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, en-gb, en;q=0.8, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, "en_GB", To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, fr;q=0.7, fr-fr;q=0.8"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, "fr_FR", To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, ru, it;q=0.8, de;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); end Test_Locales; end ASF.Applications.Main.Tests;
Update and add some locale test
Update and add some locale test
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
ec2c1575f61497b8cf605152f9dd4edba7e416d5
src/util-encoders-hmac-sha1.adb
src/util-encoders-hmac-sha1.adb
----------------------------------------------------------------------- -- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code -- 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.Encoders.Base16; with Util.Encoders.Base64; -- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package body Util.Encoders.HMAC.SHA1 is -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA1 code in binary. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Hash_Array is Ctx : Context; Result : Util.Encoders.SHA1.Hash_Array; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish (Ctx, Result); return Result; end Sign; -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Digest is Ctx : Context; Result : Util.Encoders.SHA1.Digest; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish (Ctx, Result); return Result; end Sign; -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA1 code as base64 string. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. -- ------------------------------ function Sign_Base64 (Key : in String; Data : in String; URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest is Ctx : Context; Result : Util.Encoders.SHA1.Base64_Digest; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish_Base64 (Ctx, Result, URL); return Result; end Sign_Base64; -- ------------------------------ -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. -- ------------------------------ procedure Set_Key (E : in out Context; Key : in String) is Buf : Ada.Streams.Stream_Element_Array (1 .. Key'Length); for Buf'Address use Key'Address; pragma Import (Ada, Buf); begin Set_Key (E, Buf); end Set_Key; IPAD : constant Ada.Streams.Stream_Element := 16#36#; OPAD : constant Ada.Streams.Stream_Element := 16#5c#; -- ------------------------------ -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. -- ------------------------------ procedure Set_Key (E : in out Context; Key : in Ada.Streams.Stream_Element_Array) is use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; begin -- Reduce the key if Key'Length > 64 then Util.Encoders.SHA1.Update (E.SHA, Key); Util.Encoders.SHA1.Finish (E.SHA, E.Key (0 .. 19)); E.Key_Len := 19; else E.Key_Len := Key'Length - 1; E.Key (0 .. E.Key_Len) := Key; end if; -- Hash the key in the SHA1 context. declare Block : Ada.Streams.Stream_Element_Array (0 .. 63); begin for I in 0 .. E.Key_Len loop Block (I) := IPAD xor E.Key (I); end loop; for I in E.Key_Len + 1 .. 63 loop Block (I) := IPAD; end loop; Util.Encoders.SHA1.Update (E.SHA, Block); end; end Set_Key; -- ------------------------------ -- Update the hash with the string. -- ------------------------------ procedure Update (E : in out Context; S : in String) is begin Util.Encoders.SHA1.Update (E.SHA, S); end Update; -- ------------------------------ -- Update the hash with the string. -- ------------------------------ procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array) is begin Util.Encoders.SHA1.Update (E.SHA, S); end Update; -- ------------------------------ -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>. -- ------------------------------ procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA1.Hash_Array) is use type Ada.Streams.Stream_Element; use type Ada.Streams.Stream_Element_Offset; begin Util.Encoders.SHA1.Finish (E.SHA, Hash); -- Hash the key in the SHA1 context. declare Block : Ada.Streams.Stream_Element_Array (0 .. 63); begin for I in 0 .. E.Key_Len loop Block (I) := OPAD xor E.Key (I); end loop; if E.Key_Len < 63 then for I in E.Key_Len + 1 .. 63 loop Block (I) := OPAD; end loop; end if; Util.Encoders.SHA1.Update (E.SHA, Block); end; Util.Encoders.SHA1.Update (E.SHA, Hash); Util.Encoders.SHA1.Finish (E.SHA, Hash); end Finish; -- ------------------------------ -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>. -- ------------------------------ procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA1.Digest) is Buf : Ada.Streams.Stream_Element_Array (1 .. Hash'Length); for Buf'Address use Hash'Address; pragma Import (Ada, Buf); H : Util.Encoders.SHA1.Hash_Array; B : Util.Encoders.Base16.Encoder; Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; begin Finish (E, H); B.Transform (Data => H, Into => Buf, Last => Last, Encoded => Encoded); end Finish; -- ------------------------------ -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. -- ------------------------------ procedure Finish_Base64 (E : in out Context; Hash : out Util.Encoders.SHA1.Base64_Digest; URL : in Boolean := False) is Buf : Ada.Streams.Stream_Element_Array (1 .. Hash'Length); for Buf'Address use Hash'Address; pragma Import (Ada, Buf); H : Util.Encoders.SHA1.Hash_Array; B : Util.Encoders.Base64.Encoder; Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; begin Finish (E, H); B.Set_URL_Mode (URL); B.Transform (Data => H, Into => Buf, Last => Last, Encoded => Encoded); end Finish_Base64; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is begin null; end Transform; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context) is begin null; end Initialize; end Util.Encoders.HMAC.SHA1;
----------------------------------------------------------------------- -- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code -- 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.Encoders.Base16; with Util.Encoders.Base64; -- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package body Util.Encoders.HMAC.SHA1 is -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA1 code in binary. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Hash_Array is Ctx : Context; Result : Util.Encoders.SHA1.Hash_Array; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish (Ctx, Result); return Result; end Sign; -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Digest is Ctx : Context; Result : Util.Encoders.SHA1.Digest; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish (Ctx, Result); return Result; end Sign; -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA1 code as base64 string. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. -- ------------------------------ function Sign_Base64 (Key : in String; Data : in String; URL : in Boolean := False) return Util.Encoders.SHA1.Base64_Digest is Ctx : Context; Result : Util.Encoders.SHA1.Base64_Digest; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish_Base64 (Ctx, Result, URL); return Result; end Sign_Base64; -- ------------------------------ -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. -- ------------------------------ procedure Set_Key (E : in out Context; Key : in String) is Buf : Ada.Streams.Stream_Element_Array (1 .. Key'Length); for Buf'Address use Key'Address; pragma Import (Ada, Buf); begin Set_Key (E, Buf); end Set_Key; IPAD : constant Ada.Streams.Stream_Element := 16#36#; OPAD : constant Ada.Streams.Stream_Element := 16#5c#; -- ------------------------------ -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. -- ------------------------------ procedure Set_Key (E : in out Context; Key : in Ada.Streams.Stream_Element_Array) is use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; begin -- Reduce the key if Key'Length > 64 then Util.Encoders.SHA1.Update (E.SHA, Key); Util.Encoders.SHA1.Finish (E.SHA, E.Key (0 .. 19)); E.Key_Len := 19; else E.Key_Len := Key'Length - 1; E.Key (0 .. E.Key_Len) := Key; end if; -- Hash the key in the SHA1 context. declare Block : Ada.Streams.Stream_Element_Array (0 .. 63); begin for I in 0 .. E.Key_Len loop Block (I) := IPAD xor E.Key (I); end loop; for I in E.Key_Len + 1 .. 63 loop Block (I) := IPAD; end loop; Util.Encoders.SHA1.Update (E.SHA, Block); end; end Set_Key; -- ------------------------------ -- Update the hash with the string. -- ------------------------------ procedure Update (E : in out Context; S : in String) is begin Util.Encoders.SHA1.Update (E.SHA, S); end Update; -- ------------------------------ -- Update the hash with the string. -- ------------------------------ procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array) is begin Util.Encoders.SHA1.Update (E.SHA, S); end Update; -- ------------------------------ -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>. -- ------------------------------ procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA1.Hash_Array) is use type Ada.Streams.Stream_Element; use type Ada.Streams.Stream_Element_Offset; begin Util.Encoders.SHA1.Finish (E.SHA, Hash); -- Hash the key in the SHA1 context. declare Block : Ada.Streams.Stream_Element_Array (0 .. 63); begin for I in 0 .. E.Key_Len loop Block (I) := OPAD xor E.Key (I); end loop; if E.Key_Len < 63 then for I in E.Key_Len + 1 .. 63 loop Block (I) := OPAD; end loop; end if; Util.Encoders.SHA1.Update (E.SHA, Block); end; Util.Encoders.SHA1.Update (E.SHA, Hash); Util.Encoders.SHA1.Finish (E.SHA, Hash); end Finish; -- ------------------------------ -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>. -- ------------------------------ procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA1.Digest) is Buf : Ada.Streams.Stream_Element_Array (1 .. Hash'Length); for Buf'Address use Hash'Address; pragma Import (Ada, Buf); H : Util.Encoders.SHA1.Hash_Array; B : Util.Encoders.Base16.Encoder; Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; begin Finish (E, H); B.Transform (Data => H, Into => Buf, Last => Last, Encoded => Encoded); end Finish; -- ------------------------------ -- Computes the HMAC-SHA1 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. -- ------------------------------ procedure Finish_Base64 (E : in out Context; Hash : out Util.Encoders.SHA1.Base64_Digest; URL : in Boolean := False) is Buf : Ada.Streams.Stream_Element_Array (1 .. Hash'Length); for Buf'Address use Hash'Address; pragma Import (Ada, Buf); H : Util.Encoders.SHA1.Hash_Array; B : Util.Encoders.Base64.Encoder; Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; begin Finish (E, H); B.Set_URL_Mode (URL); B.Transform (Data => H, Into => Buf, Last => Last, Encoded => Encoded); end Finish_Base64; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is begin null; end Transform; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context) is begin null; end Initialize; end Util.Encoders.HMAC.SHA1;
Change the Transformer interface to accept in out parameter for the Transformer
Change the Transformer interface to accept in out parameter for the Transformer
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f674fec78b21d6012f7c0e311a865562fb7ba3ac
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with Util.Events; with MAT.Memory.Events; with MAT.Readers; with Ada.Containers.Ordered_Maps; package MAT.Memory.Targets is type Target_Memory is record Reader : MAT.Readers.Reader_Access; Memory_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type; -- Event_Channel : MAT.Memory.Events.Memory_Event_Channel.Channel; end record; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); type Size_Info_Type is record Count : Natural; end record; use type MAT.Types.Target_Size; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map); end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with Util.Events; with MAT.Memory.Events; with MAT.Readers; with Ada.Containers.Ordered_Maps; package MAT.Memory.Targets is type Target_Memory is limited record Reader : MAT.Readers.Reader_Access; Memory_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type; -- Event_Channel : MAT.Memory.Events.Memory_Event_Channel.Channel; end record; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); type Size_Info_Type is record Count : Natural; end record; use type MAT.Types.Target_Size; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type; end Memory_Allocator; end MAT.Memory.Targets;
Define the Memory_Allocator protected and private type. Define the Probe_Malloc operation for the protected type.
Define the Memory_Allocator protected and private type. Define the Probe_Malloc operation for the protected type.
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ecb672acd0ac07d7d425e7dec48a78808ce8535e
regtests/util-streams-texts-tests.ads
regtests/util-streams-texts-tests.ads
----------------------------------------------------------------------- -- streams.texts.tests -- Unit tests for text streams -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Streams.Texts.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test reading a text stream. procedure Test_Read_Line (T : in out Test); end Util.Streams.Texts.Tests;
----------------------------------------------------------------------- -- streams.texts.tests -- Unit tests for text streams -- Copyright (C) 2012, 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.Tests; package Util.Streams.Texts.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test reading a text stream. procedure Test_Read_Line (T : in out Test); -- Write on a text stream converting an integer and writing it. procedure Test_Write_Integer (T : in out Test); end Util.Streams.Texts.Tests;
Add Test_Write_Integer procedure
Add Test_Write_Integer procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2710bfea80fc5a7034833e3dab76a889d5571fcb
regtests/security-oauth-servers-tests.adb
regtests/security-oauth-servers-tests.adb
----------------------------------------------------------------------- -- Security-oauth-servers-tests - Unit tests for server side OAuth -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Security.Auth.Tests; with Security.OAuth.File_Registry; package body Security.OAuth.Servers.Tests is use Auth.Tests; use File_Registry; package Caller is new Util.Test_Caller (Test, "Security.OAuth.Servers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Find_Application", Test_Application_Manager'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Verify", Test_User_Verify'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Token", Test_Token_Password'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Authenticate", Test_Bad_Token'Access); Caller.Add_Test (Suite, "Test Security.OAuth.File_Registry.Load", Test_Load_Registry'Access); end Add_Tests; -- ------------------------------ -- Test the application manager. -- ------------------------------ procedure Test_Application_Manager (T : in out Test) is Manager : File_Application_Manager; App : Application; begin App.Set_Application_Identifier ("my-app-id"); App.Set_Application_Secret ("my-secret"); App.Set_Application_Callback ("my-callback"); Manager.Add_Application (App); -- Check that we can find our application. declare A : constant Application'Class := Manager.Find_Application ("my-app-id"); begin Util.Tests.Assert_Equals (T, "my-app-id", A.Get_Application_Identifier, "Invalid application returned by Find"); end; -- Check that an exception is raised for an invalid client ID. begin declare A : constant Application'Class := Manager.Find_Application ("unkown-app-id"); begin Util.Tests.Fail (T, "Found the application " & A.Get_Application_Identifier); end; exception when Invalid_Application => null; end; end Test_Application_Manager; -- ------------------------------ -- Test the user registration and verification. -- ------------------------------ procedure Test_User_Verify (T : in out Test) is Manager : File_Realm_Manager; Auth : Principal_Access; begin Manager.Add_User ("Gandalf", "Mithrandir"); Manager.Verify ("Gandalf", "mithrandir", Auth); T.Assert (Auth = null, "Verify password should fail with an invalid password"); Manager.Verify ("Sauron", "Mithrandir", Auth); T.Assert (Auth = null, "Verify password should fail with an invalid user"); Manager.Verify ("Gandalf", "Mithrandir", Auth); T.Assert (Auth /= null, "Verify password operation failed for a good user/password"); end Test_User_Verify; -- ------------------------------ -- Test the token operation that produces an access token from user/password. -- RFC 6749: Section 4.3. Resource Owner Password Credentials Grant -- ------------------------------ procedure Test_Token_Password (T : in out Test) is use type Util.Strings.Name_Access; Apps : aliased File_Application_Manager; Realm : aliased File_Realm_Manager; Manager : Auth_Manager; App : Application; Grant : Grant_Type; Auth_Grant : Grant_Type; Params : Test_Parameters; begin -- Add one test application. App.Set_Application_Identifier ("my-app-id"); App.Set_Application_Secret ("my-secret"); App.Set_Application_Callback ("my-callback"); Apps.Add_Application (App); -- Add one test user. Realm.Add_User ("Gandalf", "Mithrandir"); -- Configure the auth manager. Manager.Set_Application_Manager (Apps'Unchecked_Access); Manager.Set_Realm_Manager (Realm'Unchecked_Access); Manager.Set_Private_Key ("server-private-key-no-so-secure"); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is missing"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, ""); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, "unkown-app"); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is invalid"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, "my-app-id"); Params.Set_Parameter (Security.OAuth.GRANT_TYPE, ""); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty"); Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the user/password is missing"); Params.Set_Parameter (Security.OAuth.USERNAME, "Gandalf"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the password is missing"); Params.Set_Parameter (Security.OAuth.PASSWORD, "test"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the password is invalid"); Params.Set_Parameter (Security.OAuth.PASSWORD, "Mithrandir"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct"); T.Assert (Grant.Error = null, "Expecting null error"); T.Assert (Length (Grant.Token) > 20, "Expecting a token with some reasonable size"); T.Assert (Grant.Auth /= null, "Expecting a non null auth principal"); Util.Tests.Assert_Equals (T, "Gandalf", Grant.Auth.Get_Name, "Invalid user name in the principal"); -- Verify the access token. for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Request = Access_Grant, "Expecting Access_Grant for the authenticate"); T.Assert (Auth_Grant.Status = Valid_Grant, "Expecting Valid_Grant when the access token is checked"); T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token"); T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal"); end loop; -- Verify the modified access token. Manager.Authenticate (To_String (Grant.Token) & "x", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for the authenticate"); Manager.Revoke (To_String (Grant.Token)); -- Verify the access is now denied. for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Status = Revoked_Grant, "Expecting Revoked_Grant for the authenticate"); end loop; -- Change application token expiration time to 1 second. App.Expire_Timeout := 1.0; Apps.Add_Application (App); -- Make the access token. Manager.Token (Params, Grant); T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct"); -- Verify the access token. for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Request = Access_Grant, "Expecting Access_Grant for the authenticate"); T.Assert (Auth_Grant.Status = Valid_Grant, "Expecting Valid_Grant when the access token is checked"); T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token"); T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal"); end loop; -- Wait for the token to expire. delay 2.0; for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Status = Expired_Grant, "Expecting Expired when the access token is checked"); end loop; end Test_Token_Password; -- ------------------------------ -- Test the access token validation with invalid tokens (bad formed). -- ------------------------------ procedure Test_Bad_Token (T : in out Test) is Manager : Auth_Manager; Auth_Grant : Grant_Type; begin Manager.Authenticate ("x", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate (".", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("..", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("a..", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("..b", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("a..b", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); end Test_Bad_Token; -- ------------------------------ -- Test the loading configuration files for the File_Registry. -- ------------------------------ procedure Test_Load_Registry (T : in out Test) is Apps : aliased File_Application_Manager; Realm : aliased File_Realm_Manager; Manager : Auth_Manager; Grant : Grant_Type; Auth_Grant : Grant_Type; Params : Test_Parameters; begin Apps.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "apps"); Realm.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "users"); -- Configure the auth manager. Manager.Set_Application_Manager (Apps'Unchecked_Access); Manager.Set_Realm_Manager (Realm'Unchecked_Access); Manager.Set_Private_Key ("server-private-key-no-so-secure"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, "app-id-1"); Params.Set_Parameter (Security.OAuth.CLIENT_SECRET, "app-secret-1"); Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password"); Params.Set_Parameter (Security.OAuth.USERNAME, "joe"); Params.Set_Parameter (Security.OAuth.PASSWORD, "test"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct"); end Test_Load_Registry; end Security.OAuth.Servers.Tests;
----------------------------------------------------------------------- -- Security-oauth-servers-tests - Unit tests for server side OAuth -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Security.Auth.Tests; with Security.OAuth.File_Registry; package body Security.OAuth.Servers.Tests is use Auth.Tests; use File_Registry; package Caller is new Util.Test_Caller (Test, "Security.OAuth.Servers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Find_Application", Test_Application_Manager'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Verify", Test_User_Verify'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Token", Test_Token_Password'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Authenticate", Test_Bad_Token'Access); Caller.Add_Test (Suite, "Test Security.OAuth.File_Registry.Load", Test_Load_Registry'Access); end Add_Tests; -- ------------------------------ -- Test the application manager. -- ------------------------------ procedure Test_Application_Manager (T : in out Test) is Manager : File_Application_Manager; App : Application; begin App.Set_Application_Identifier ("my-app-id"); App.Set_Application_Secret ("my-secret"); App.Set_Application_Callback ("my-callback"); Manager.Add_Application (App); -- Check that we can find our application. declare A : constant Application'Class := Manager.Find_Application ("my-app-id"); begin Util.Tests.Assert_Equals (T, "my-app-id", A.Get_Application_Identifier, "Invalid application returned by Find"); end; -- Check that an exception is raised for an invalid client ID. begin declare A : constant Application'Class := Manager.Find_Application ("unkown-app-id"); begin Util.Tests.Fail (T, "Found the application " & A.Get_Application_Identifier); end; exception when Invalid_Application => null; end; end Test_Application_Manager; -- ------------------------------ -- Test the user registration and verification. -- ------------------------------ procedure Test_User_Verify (T : in out Test) is Manager : File_Realm_Manager; Auth : Principal_Access; begin Manager.Add_User ("Gandalf", "Mithrandir"); Manager.Verify ("Gandalf", "mithrandir", Auth); T.Assert (Auth = null, "Verify password should fail with an invalid password"); Manager.Verify ("Sauron", "Mithrandir", Auth); T.Assert (Auth = null, "Verify password should fail with an invalid user"); Manager.Verify ("Gandalf", "Mithrandir", Auth); T.Assert (Auth /= null, "Verify password operation failed for a good user/password"); end Test_User_Verify; -- ------------------------------ -- Test the token operation that produces an access token from user/password. -- RFC 6749: Section 4.3. Resource Owner Password Credentials Grant -- ------------------------------ procedure Test_Token_Password (T : in out Test) is use type Util.Strings.Name_Access; Apps : aliased File_Application_Manager; Realm : aliased File_Realm_Manager; Manager : Auth_Manager; App : Application; Grant : Grant_Type; Auth_Grant : Grant_Type; Params : Test_Parameters; begin -- Add one test application. App.Set_Application_Identifier ("my-app-id"); App.Set_Application_Secret ("my-secret"); App.Set_Application_Callback ("my-callback"); Apps.Add_Application (App); -- Add one test user. Realm.Add_User ("Gandalf", "Mithrandir"); -- Configure the auth manager. Manager.Set_Application_Manager (Apps'Unchecked_Access); Manager.Set_Realm_Manager (Realm'Unchecked_Access); Manager.Set_Private_Key ("server-private-key-no-so-secure"); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is missing"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, ""); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, "unkown-app"); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is invalid"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, "my-app-id"); Params.Set_Parameter (Security.OAuth.GRANT_TYPE, ""); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty"); Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the user/password is missing"); Params.Set_Parameter (Security.OAuth.USERNAME, "Gandalf"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the password is missing"); Params.Set_Parameter (Security.OAuth.PASSWORD, "test"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the password is invalid"); Params.Set_Parameter (Security.OAuth.PASSWORD, "Mithrandir"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the client_secret is invalid"); Params.Set_Parameter (Security.OAuth.CLIENT_SECRET, "my-secret"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct"); T.Assert (Grant.Error = null, "Expecting null error"); T.Assert (Length (Grant.Token) > 20, "Expecting a token with some reasonable size"); T.Assert (Grant.Auth /= null, "Expecting a non null auth principal"); Util.Tests.Assert_Equals (T, "Gandalf", Grant.Auth.Get_Name, "Invalid user name in the principal"); -- Verify the access token. for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Request = Access_Grant, "Expecting Access_Grant for the authenticate"); T.Assert (Auth_Grant.Status = Valid_Grant, "Expecting Valid_Grant when the access token is checked"); T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token"); T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal"); end loop; -- Verify the modified access token. Manager.Authenticate (To_String (Grant.Token) & "x", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for the authenticate"); Manager.Revoke (To_String (Grant.Token)); -- Verify the access is now denied. for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Status = Revoked_Grant, "Expecting Revoked_Grant for the authenticate"); end loop; -- Change application token expiration time to 1 second. App.Expire_Timeout := 1.0; Apps.Add_Application (App); -- Make the access token. Manager.Token (Params, Grant); T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct"); -- Verify the access token. for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Request = Access_Grant, "Expecting Access_Grant for the authenticate"); T.Assert (Auth_Grant.Status = Valid_Grant, "Expecting Valid_Grant when the access token is checked"); T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token"); T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal"); end loop; -- Wait for the token to expire. delay 2.0; for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Status = Expired_Grant, "Expecting Expired when the access token is checked"); end loop; end Test_Token_Password; -- ------------------------------ -- Test the access token validation with invalid tokens (bad formed). -- ------------------------------ procedure Test_Bad_Token (T : in out Test) is Manager : Auth_Manager; Auth_Grant : Grant_Type; begin Manager.Authenticate ("x", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate (".", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("..", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("a..", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("..b", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("a..b", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); end Test_Bad_Token; -- ------------------------------ -- Test the loading configuration files for the File_Registry. -- ------------------------------ procedure Test_Load_Registry (T : in out Test) is Apps : aliased File_Application_Manager; Realm : aliased File_Realm_Manager; Manager : Auth_Manager; Grant : Grant_Type; Auth_Grant : Grant_Type; Params : Test_Parameters; begin Apps.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "apps"); Realm.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "users"); -- Configure the auth manager. Manager.Set_Application_Manager (Apps'Unchecked_Access); Manager.Set_Realm_Manager (Realm'Unchecked_Access); Manager.Set_Private_Key ("server-private-key-no-so-secure"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, "app-id-1"); Params.Set_Parameter (Security.OAuth.CLIENT_SECRET, "app-secret-1"); Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password"); Params.Set_Parameter (Security.OAuth.USERNAME, "joe"); Params.Set_Parameter (Security.OAuth.PASSWORD, "test"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct"); end Test_Load_Registry; end Security.OAuth.Servers.Tests;
Fix unit test to verify the password authenticate
Fix unit test to verify the password authenticate
Ada
apache-2.0
stcarrez/ada-security
e6879b77fd398accc007ca5b94858aea682a88ea
testcases/stored_procs/stored_procs.adb
testcases/stored_procs/stored_procs.adb
with AdaBase; with Connect; with Ada.Text_IO; with AdaBase.Results.Sets; procedure Stored_Procs is package CON renames Connect; package TIO renames Ada.Text_IO; package ARS renames AdaBase.Results.Sets; stmt_acc : CON.Stmt_Type_access; procedure dump_result; procedure dump_result is function pad (S : String) return String; function pad (S : String) return String is field : String (1 .. 15) := (others => ' '); len : Natural := S'Length; begin field (1 .. len) := S; return field; end pad; row : ARS.Datarow; numcols : constant Natural := stmt_acc.column_count; begin for c in Natural range 1 .. numcols loop TIO.Put (pad (stmt_acc.column_name (c))); end loop; TIO.Put_Line (""); for c in Natural range 1 .. numcols loop TIO.Put ("============== "); end loop; TIO.Put_Line (""); loop row := stmt_acc.fetch_next; exit when row.data_exhausted; for c in Natural range 1 .. numcols loop TIO.Put (pad (row.column (c).as_string)); end loop; TIO.Put_Line (""); end loop; TIO.Put_Line (""); end dump_result; sql : constant String := "CALL multiple_rowsets"; set_fetched : Boolean; set_present : Boolean; begin CON.connect_database; declare stmt : aliased CON.Stmt_Type := CON.DR.query (sql); begin if stmt.successful then set_fetched := True; else TIO.Put_Line ("Stored procedures not supported on " & CON.DR.trait_driver); end if; set_fetched := stmt.successful; stmt_acc := stmt'Unchecked_Access; loop if set_fetched then dump_result; end if; stmt.fetch_next_set (set_present, set_fetched); exit when not set_present; end loop; end; CON.DR.disconnect; end Stored_Procs;
with AdaBase; with Connect; with Ada.Text_IO; with AdaBase.Results.Sets; procedure Stored_Procs is package CON renames Connect; package TIO renames Ada.Text_IO; package ARS renames AdaBase.Results.Sets; stmt_acc : CON.Stmt_Type_access; procedure dump_result; procedure dump_result is function pad (S : String) return String; function pad (S : String) return String is field : String (1 .. 15) := (others => ' '); len : Natural := S'Length; begin field (1 .. len) := S; return field; end pad; row : ARS.Datarow; numcols : constant Natural := stmt_acc.column_count; begin for c in Natural range 1 .. numcols loop TIO.Put (pad (stmt_acc.column_name (c))); end loop; TIO.Put_Line (""); for c in Natural range 1 .. numcols loop TIO.Put ("============== "); end loop; TIO.Put_Line (""); loop row := stmt_acc.fetch_next; exit when row.data_exhausted; for c in Natural range 1 .. numcols loop TIO.Put (pad (row.column (c).as_string)); end loop; TIO.Put_Line (""); end loop; TIO.Put_Line (""); end dump_result; sql : constant String := "CALL multiple_rowsets"; set_fetched : Boolean; set_present : Boolean; begin CON.connect_database; declare stmt : aliased CON.Stmt_Type := CON.DR.call_stored_procedure ("multiple_rowsets", ""); begin if stmt.successful then set_fetched := True; else TIO.Put_Line ("Stored procedures not supported on " & CON.DR.trait_driver); end if; set_fetched := stmt.successful; stmt_acc := stmt'Unchecked_Access; loop if set_fetched then dump_result; end if; stmt.fetch_next_set (set_present, set_fetched); exit when not set_present; end loop; end; CON.DR.disconnect; end Stored_Procs;
Modify stored procs testcase to use new call_stored_procedure function
Modify stored procs testcase to use new call_stored_procedure function
Ada
isc
jrmarino/AdaBase
1d4dc2c1cab89c1a702612d495bd19688d4b0ac6
src/asf-applications-messages-factory.adb
src/asf-applications-messages-factory.adb
----------------------------------------------------------------------- -- applications.messages-factory -- Application Message Factory -- 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.Exceptions; with Util.Log.Loggers; with Util.Properties.Bundles; with Util.Beans.Objects; with Util.Locales; with ASF.Locales; with ASF.Applications.Main; package body ASF.Applications.Messages.Factory is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Messages.Factory"); -- ------------------------------ -- Get a localized message. The message identifier is composed of a resource bundle name -- prefix and a bundle key. The prefix and key are separated by the first '.'. -- If the message identifier does not contain any prefix, the default bundle is "messages". -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String) return String is Pos : constant Natural := Util.Strings.Index (Message_Id, '.'); Locale : constant Util.Locales.Locale := Context.Get_Locale; App : constant access ASF.Applications.Main.Application'Class := Context.Get_Application; Bundle : ASF.Locales.Bundle; begin if Pos > 0 then App.Load_Bundle (Name => Message_Id (Message_Id'First .. Pos - 1), Locale => Util.Locales.To_String (Locale), Bundle => Bundle); return Bundle.Get (Message_Id (Pos + 1 .. Message_Id'Last), Message_Id (Pos + 1 .. Message_Id'Last)); else App.Load_Bundle (Name => "messages", Locale => Util.Locales.To_String (Locale), Bundle => Bundle); return Bundle.Get (Message_Id, Message_Id); end if; exception when E : Util.Properties.Bundles.NO_BUNDLE => Log.Error ("Cannot localize {0}: {1}", Message_Id, Ada.Exceptions.Exception_Message (E)); return Message_Id; end Get_Message; -- ------------------------------ -- Build a localized message. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Severity : in Messages.Severity := ERROR) return Message is Msg : constant String := Get_Message (Context, Message_Id); Result : Message; begin Result.Summary := Ada.Strings.Unbounded.To_Unbounded_String (Msg); Result.Kind := Severity; return Result; end Get_Message; -- ------------------------------ -- Build a localized message and format the message with one argument. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Severity : in Messages.Severity := ERROR) return Message is Args : ASF.Utils.Object_Array (1 .. 1); begin Args (1) := Util.Beans.Objects.To_Object (Param1); return Get_Message (Context, Message_Id, Args, Severity); end Get_Message; -- ------------------------------ -- Build a localized message and format the message with two argument. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Param2 : in String; Severity : in Messages.Severity := ERROR) return Message is Args : ASF.Utils.Object_Array (1 .. 2); begin Args (1) := Util.Beans.Objects.To_Object (Param1); Args (2) := Util.Beans.Objects.To_Object (Param2); return Get_Message (Context, Message_Id, Args, Severity); end Get_Message; -- ------------------------------ -- Build a localized message and format the message with some arguments. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Args : in ASF.Utils.Object_Array; Severity : in Messages.Severity := ERROR) return Message is Msg : constant String := Get_Message (Context, Message_Id); Result : Message; begin Result.Kind := Severity; ASF.Utils.Formats.Format (Msg, Args, Result.Summary); return Result; end Get_Message; -- ------------------------------ -- Add a localized global message in the faces context. -- ------------------------------ procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Severity : in Messages.Severity := ERROR) is Msg : constant Message := Get_Message (Context, Message_Id, Param1, Severity); begin Context.Add_Message (Client_Id => "", Message => Msg); end Add_Message; -- ------------------------------ -- Add a localized global message in the faces context. -- ------------------------------ procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Severity : in Messages.Severity := ERROR) is Msg : constant Message := Get_Message (Context, Message_Id, Severity); begin Context.Add_Message (Client_Id => "", Message => Msg); end Add_Message; -- ------------------------------ -- Add a localized global message in the current faces context. -- ------------------------------ procedure Add_Message (Message_Id : in String; Severity : in Messages.Severity := ERROR) is Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin Add_Message (Context.all, Message_Id, Severity); end Add_Message; end ASF.Applications.Messages.Factory;
----------------------------------------------------------------------- -- applications.messages-factory -- Application Message Factory -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with Util.Properties.Bundles; with Util.Beans.Objects; with Util.Locales; with ASF.Locales; with ASF.Applications.Main; package body ASF.Applications.Messages.Factory is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Messages.Factory"); -- ------------------------------ -- Get a localized message. The message identifier is composed of a resource bundle name -- prefix and a bundle key. The prefix and key are separated by the first '.'. -- If the message identifier does not contain any prefix, the default bundle is "messages". -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String) return String is Pos : constant Natural := Util.Strings.Index (Message_Id, '.'); Locale : constant Util.Locales.Locale := Context.Get_Locale; App : constant access ASF.Applications.Main.Application'Class := Context.Get_Application; Bundle : ASF.Locales.Bundle; begin if Pos > 0 then App.Load_Bundle (Name => Message_Id (Message_Id'First .. Pos - 1), Locale => Util.Locales.To_String (Locale), Bundle => Bundle); return Bundle.Get (Message_Id (Pos + 1 .. Message_Id'Last), Message_Id (Pos + 1 .. Message_Id'Last)); else App.Load_Bundle (Name => "messages", Locale => Util.Locales.To_String (Locale), Bundle => Bundle); return Bundle.Get (Message_Id, Message_Id); end if; exception when E : Util.Properties.Bundles.NO_BUNDLE => Log.Error ("Cannot localize {0}: {1}", Message_Id, Ada.Exceptions.Exception_Message (E)); return Message_Id; end Get_Message; -- ------------------------------ -- Build a localized message. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Severity : in Messages.Severity := ERROR) return Message is Msg : constant String := Get_Message (Context, Message_Id); Result : Message; begin Result.Summary := Ada.Strings.Unbounded.To_Unbounded_String (Msg); Result.Kind := Severity; return Result; end Get_Message; -- ------------------------------ -- Build a localized message and format the message with one argument. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Severity : in Messages.Severity := ERROR) return Message is Args : ASF.Utils.Object_Array (1 .. 1); begin Args (1) := Util.Beans.Objects.To_Object (Param1); return Get_Message (Context, Message_Id, Args, Severity); end Get_Message; -- ------------------------------ -- Build a localized message and format the message with two argument. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Param2 : in String; Severity : in Messages.Severity := ERROR) return Message is Args : ASF.Utils.Object_Array (1 .. 2); begin Args (1) := Util.Beans.Objects.To_Object (Param1); Args (2) := Util.Beans.Objects.To_Object (Param2); return Get_Message (Context, Message_Id, Args, Severity); end Get_Message; -- ------------------------------ -- Build a localized message and format the message with some arguments. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Args : in ASF.Utils.Object_Array; Severity : in Messages.Severity := ERROR) return Message is Msg : constant String := Get_Message (Context, Message_Id); Result : Message; begin Result.Kind := Severity; ASF.Utils.Formats.Format (Msg, Args, Result.Summary); return Result; end Get_Message; -- ------------------------------ -- Add a localized global message in the faces context. -- ------------------------------ procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Severity : in Messages.Severity := ERROR) is Msg : constant Message := Get_Message (Context, Message_Id, Param1, Severity); begin Context.Add_Message (Client_Id => "", Message => Msg); end Add_Message; -- ------------------------------ -- Add a localized global message in the faces context. -- ------------------------------ procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Severity : in Messages.Severity := ERROR) is Msg : constant Message := Get_Message (Context, Message_Id, Severity); begin Context.Add_Message (Client_Id => "", Message => Msg); end Add_Message; -- ------------------------------ -- Add a localized global message in the current faces context. -- ------------------------------ procedure Add_Message (Message_Id : in String; Severity : in Messages.Severity := ERROR) is Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin Add_Message (Context.all, Message_Id, Severity); end Add_Message; -- ------------------------------ -- Add a localized field message in the current faces context. The message is associated -- with the component identified by <tt>Client_Id</tt>. -- ------------------------------ procedure Add_Field_Message (Client_Id : in String; Message_Id : in String; Severity : in Messages.Severity := ERROR) is Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Msg : constant Message := Get_Message (Context.all, Message_Id, Severity); begin Context.Add_Message (Client_Id => Client_Id, Message => Msg); end Add_Field_Message; end ASF.Applications.Messages.Factory;
Implement the Add_Field_Message procedure to associate a message to a component field
Implement the Add_Field_Message procedure to associate a message to a component field
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
fcc961e59f19287a79cec924e3b1777a5f535caf
src/ado-utils-serialize.adb
src/ado-utils-serialize.adb
----------------------------------------------------------------------- -- ado-utils-serialize -- Utility operations for JSON/XML serialization -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.Utils.Serialize is -- ------------------------------ -- Write the entity to the serialization stream (JSON/XML). -- ------------------------------ procedure Write_Entity (Stream : in out Util.Serialize.IO.Output_Stream'Class; Name : in String; Value : in ADO.Identifier) is begin Stream.Write_Long_Entity (Name, Long_Long_Integer (Value)); end Write_Entity; -- ------------------------------ -- Write the entity to the serialization stream (JSON/XML). -- ------------------------------ procedure Write_Entity (Stream : in out Util.Serialize.IO.Output_Stream'Class; Name : in String; Value : in ADO.Objects.Object_Key) is begin case Value.Of_Type is when ADO.Objects.KEY_INTEGER => Write_Entity (Stream, Name, ADO.Objects.Get_Value (Value)); when ADO.Objects.KEY_STRING => Stream.Write_Entity (Name, ADO.Objects.Get_Value (Value)); end case; end Write_Entity; end ADO.Utils.Serialize;
----------------------------------------------------------------------- -- ado-utils-serialize -- Utility operations for JSON/XML serialization -- Copyright (C) 2016, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Schemas; package body ADO.Utils.Serialize is -- ------------------------------ -- Write the entity to the serialization stream (JSON/XML). -- ------------------------------ procedure Write_Entity (Stream : in out Util.Serialize.IO.Output_Stream'Class; Name : in String; Value : in ADO.Identifier) is begin Stream.Write_Long_Entity (Name, Long_Long_Integer (Value)); end Write_Entity; -- ------------------------------ -- Write the entity to the serialization stream (JSON/XML). -- ------------------------------ procedure Write_Entity (Stream : in out Util.Serialize.IO.Output_Stream'Class; Name : in String; Value : in ADO.Objects.Object_Key) is begin case Value.Of_Type is when ADO.Objects.KEY_INTEGER => Write_Entity (Stream, Name, ADO.Objects.Get_Value (Value)); when ADO.Objects.KEY_STRING => Stream.Write_Entity (Name, ADO.Objects.Get_Value (Value)); end case; end Write_Entity; -- ------------------------------ -- Write the SQL query results to the serialization stream (JSON/XML). -- ------------------------------ procedure Write_Query (Stream : in out Util.Serialize.IO.Output_Stream'Class; Name : in String; Query : in out ADO.Statements.Query_Statement) is use ADO.Schemas; Column_Count : Natural; begin Stream.Start_Array (Name); if Query.Has_Elements then Column_Count := Query.Get_Column_Count; while Query.Has_Elements loop Stream.Start_Entity (""); for I in 1 .. Column_Count loop declare Name : constant String := Query.Get_Column_Name (I - 1); begin if Query.Is_Null (I - 1) then Stream.Write_Null_Entity (Name); else case Query.Get_Column_Type (I - 1) is -- Boolean column when T_BOOLEAN => Stream.Write_Entity (Name, Query.Get_Boolean (I - 1)); when T_TINYINT | T_SMALLINT | T_INTEGER | T_LONG_INTEGER | T_YEAR => Stream.Write_Entity (Name, Query.Get_Integer (I - 1)); when T_FLOAT | T_DOUBLE | T_DECIMAL => Stream.Write_Null_Entity (Name); when T_ENUM => Stream.Write_Entity (Name, Query.Get_String (I - 1)); when T_TIME | T_DATE | T_DATE_TIME | T_TIMESTAMP => Stream.Write_Entity (Name, Query.Get_Time (I - 1)); when T_CHAR | T_VARCHAR => Stream.Write_Entity (Name, Query.Get_String (I - 1)); when T_BLOB => Stream.Write_Null_Entity (Name); when T_SET | T_UNKNOWN | T_NULL => Stream.Write_Null_Entity (Name); end case; end if; end; end loop; Stream.End_Entity (""); Query.Next; end loop; end if; Stream.End_Array (Name); end Write_Query; end ADO.Utils.Serialize;
Implement Write_Query to serialize the query statement in a JSON/XML stream
Implement Write_Query to serialize the query statement in a JSON/XML stream
Ada
apache-2.0
stcarrez/ada-ado
4c0da064cf8311eaf93cf8d9d73cc68f57f9420f
src/asf-components-root.adb
src/asf-components-root.adb
----------------------------------------------------------------------- -- components-root -- ASF Root View Component -- 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 ASF.Components.Base; with ASF.Components.Core.Views; package body ASF.Components.Root is use ASF; use EL.Objects; -- ------------------------------ -- Get the root node of the view. -- ------------------------------ function Get_Root (UI : in UIViewRoot) return access Base.UIComponent'Class is begin if UI.Root = null then return null; elsif UI.Root.Meta = null then return UI.Root.View; else return UI.Root.Meta; end if; end Get_Root; -- ------------------------------ -- Set the root node of the view. -- ------------------------------ procedure Set_Root (UI : in out UIViewRoot; Root : access Base.UIComponent'Class; Name : in String) is begin if UI.Root /= null then Finalize (UI); end if; UI.Root := new Root_Holder '(Ref_Counter => 1, Len => Name'Length, View => Root, Meta => null, Name => Name); end Set_Root; -- ------------------------------ -- Set the metadata component of the view. -- ------------------------------ procedure Set_Meta (UI : in out UIViewRoot) is Node : access Base.UIComponent'Class; begin if UI.Root /= null then Node := UI.Root.View; UI.Root.Meta := Node.Get_Facet (Core.Views.METADATA_FACET_NAME); if UI.Root.Meta = null then declare Iter : Base.Cursor := Base.First (Node.all); begin while Base.Has_Element (Iter) loop UI.Root.Meta := Base.Element (Iter).Get_Facet (Core.Views.METADATA_FACET_NAME); exit when UI.Root.Meta /= null; Base.Next (Iter); end loop; end; end if; end if; end Set_Meta; -- ------------------------------ -- Returns True if the view has a metadata component. -- ------------------------------ function Has_Meta (UI : in UIViewRoot) return Boolean is begin return UI.Root /= null and then UI.Root.Meta /= null; end Has_Meta; -- ------------------------------ -- Get the view identifier. -- ------------------------------ function Get_View_Id (UI : in UIViewRoot) return String is begin return UI.Root.Name; end Get_View_Id; -- ------------------------------ -- Create an identifier for a component. -- ------------------------------ procedure Create_Unique_Id (UI : in out UIViewRoot; Id : out Natural) is begin UI.Last_Id := UI.Last_Id + 1; Id := UI.Last_Id; end Create_Unique_Id; -- ------------------------------ -- Increment the reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out UIViewRoot) is begin if Object.Root /= null then Object.Root.Ref_Counter := Object.Root.Ref_Counter + 1; end if; end Adjust; Empty : ASF.Components.Base.UIComponent; -- ------------------------------ -- Free the memory held by the component tree. -- ------------------------------ overriding procedure Finalize (Object : in out UIViewRoot) is procedure Free is new Ada.Unchecked_Deallocation (Object => Root_Holder, Name => Root_Holder_Access); begin if Object.Root /= null then Object.Root.Ref_Counter := Object.Root.Ref_Counter - 1; if Object.Root.Ref_Counter = 0 then declare C : ASF.Components.Base.UIComponent_Access := Object.Root.View.all'Unchecked_Access; begin ASF.Components.Base.Steal_Root_Component (Empty, C); end; Free (Object.Root); end if; end if; end Finalize; end ASF.Components.Root;
----------------------------------------------------------------------- -- components-root -- ASF Root View Component -- Copyright (C) 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ASF.Components.Base; with ASF.Components.Core.Views; package body ASF.Components.Root is -- ------------------------------ -- Get the root node of the view. -- ------------------------------ function Get_Root (UI : in UIViewRoot) return access Base.UIComponent'Class is begin if UI.Root = null then return null; elsif UI.Root.Meta = null then return UI.Root.View; else return UI.Root.Meta; end if; end Get_Root; -- ------------------------------ -- Set the root node of the view. -- ------------------------------ procedure Set_Root (UI : in out UIViewRoot; Root : access Base.UIComponent'Class; Name : in String) is begin if UI.Root /= null then Finalize (UI); end if; UI.Root := new Root_Holder '(Ref_Counter => 1, Len => Name'Length, View => Root, Meta => null, Name => Name); end Set_Root; -- ------------------------------ -- Set the metadata component of the view. -- ------------------------------ procedure Set_Meta (UI : in out UIViewRoot) is Node : access Base.UIComponent'Class; begin if UI.Root /= null then Node := UI.Root.View; UI.Root.Meta := Node.Get_Facet (Core.Views.METADATA_FACET_NAME); if UI.Root.Meta = null then declare Iter : Base.Cursor := Base.First (Node.all); begin while Base.Has_Element (Iter) loop UI.Root.Meta := Base.Element (Iter).Get_Facet (Core.Views.METADATA_FACET_NAME); exit when UI.Root.Meta /= null; Base.Next (Iter); end loop; end; end if; end if; end Set_Meta; -- ------------------------------ -- Returns True if the view has a metadata component. -- ------------------------------ function Has_Meta (UI : in UIViewRoot) return Boolean is begin return UI.Root /= null and then UI.Root.Meta /= null; end Has_Meta; -- ------------------------------ -- Get the view identifier. -- ------------------------------ function Get_View_Id (UI : in UIViewRoot) return String is begin return UI.Root.Name; end Get_View_Id; -- ------------------------------ -- Create an identifier for a component. -- ------------------------------ procedure Create_Unique_Id (UI : in out UIViewRoot; Id : out Natural) is begin UI.Last_Id := UI.Last_Id + 1; Id := UI.Last_Id; end Create_Unique_Id; -- ------------------------------ -- Increment the reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out UIViewRoot) is begin if Object.Root /= null then Object.Root.Ref_Counter := Object.Root.Ref_Counter + 1; end if; end Adjust; Empty : ASF.Components.Base.UIComponent; -- ------------------------------ -- Free the memory held by the component tree. -- ------------------------------ overriding procedure Finalize (Object : in out UIViewRoot) is procedure Free is new Ada.Unchecked_Deallocation (Object => Root_Holder, Name => Root_Holder_Access); begin if Object.Root /= null then Object.Root.Ref_Counter := Object.Root.Ref_Counter - 1; if Object.Root.Ref_Counter = 0 then declare C : ASF.Components.Base.UIComponent_Access := Object.Root.View.all'Unchecked_Access; begin ASF.Components.Base.Steal_Root_Component (Empty, C); end; Free (Object.Root); end if; end if; end Finalize; end ASF.Components.Root;
Remove unused use clauses
Remove unused use clauses
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
2bbff20b144289afba30a4b4897d95646cc8ef35
regtests/asf-requests-tests.adb
regtests/asf-requests-tests.adb
----------------------------------------------------------------------- -- asf-requests-tests - Unit tests for requests -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with Util.Measures; with ASF.Requests.Mockup; package body ASF.Requests.Tests is use Util.Tests; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Requests.Tests"); package Caller is new Util.Test_Caller (Test, "Requests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Requests.Split_Header", Test_Split_Header'Access); Caller.Add_Test (Suite, "Test ASF.Requests.Accept_Locales", Test_Accept_Locales'Access); end Add_Tests; -- ------------------------------ -- Test the Split_Header procedure. -- ------------------------------ procedure Test_Split_Header (T : in out Test) is procedure Process_Text (Item : in String; Quality : in Quality_Type); Count : Natural := 0; procedure Process_Text (Item : in String; Quality : in Quality_Type) is begin T.Assert (Item = "text/plain" or Item = "text/html" or Item = "text/x-dvi" or Item = "text/x-c", "Invalid item: " & Item); T.Assert (Quality = 0.5 or Quality = 0.8 or Quality = 1.0, "Invalid quality"); if Item = "text/plain" then T.Assert (Quality = 0.5, "Invalid quality for " & Item); elsif Item = "text/x-dvi" or Item = "text/html" then T.Assert (Quality = 0.8, "Invalid quality for " & Item); else T.Assert (Quality = 1.0, "Invalid quality for " & Item); end if; Count := Count + 1; end Process_Text; begin Split_Header ("text/plain; q=0.5, text/html,text/x-dvi; q=0.8, text/x-c", Process_Text'Access); Util.Tests.Assert_Equals (T, 4, Count, "Invalid number of items"); end Test_Split_Header; -- ------------------------------ -- Test the Accept_Locales procedure. -- ------------------------------ procedure Test_Accept_Locales (T : in out Test) is procedure Process_Locale (Locale : in Util.Locales.Locale; Quality : in Quality_Type); use Util.Locales; Req : ASF.Requests.Mockup.Request; Count : Natural := 0; procedure Process_Locale (Locale : in Util.Locales.Locale; Quality : in Quality_Type) is Lang : constant String := Util.Locales.Get_Language (Locale); begin Log.Info ("Found locale: {0}", Util.Locales.To_String (Locale)); T.Assert (Lang = "da" or Lang = "en_GB" or Lang = "en", "Invalid lang: " & Lang); Count := Count + 1; end Process_Locale; begin Req.Set_Header ("Accept-Language", "da, en-gb;q=0.8, en;q=0.7"); Req.Accept_Locales (Process_Locale'Access); Util.Tests.Assert_Equals (T, 3, Count, "Invalid number of calls"); end Test_Accept_Locales; end ASF.Requests.Tests;
----------------------------------------------------------------------- -- asf-requests-tests - Unit tests for requests -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with ASF.Requests.Mockup; package body ASF.Requests.Tests is use Util.Tests; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Requests.Tests"); package Caller is new Util.Test_Caller (Test, "Requests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Requests.Split_Header", Test_Split_Header'Access); Caller.Add_Test (Suite, "Test ASF.Requests.Accept_Locales", Test_Accept_Locales'Access); end Add_Tests; -- ------------------------------ -- Test the Split_Header procedure. -- ------------------------------ procedure Test_Split_Header (T : in out Test) is procedure Process_Text (Item : in String; Quality : in Quality_Type); Count : Natural := 0; procedure Process_Text (Item : in String; Quality : in Quality_Type) is begin T.Assert (Item = "text/plain" or Item = "text/html" or Item = "text/x-dvi" or Item = "text/x-c", "Invalid item: " & Item); T.Assert (Quality = 0.5 or Quality = 0.8 or Quality = 1.0, "Invalid quality"); if Item = "text/plain" then T.Assert (Quality = 0.5, "Invalid quality for " & Item); elsif Item = "text/x-dvi" or Item = "text/html" then T.Assert (Quality = 0.8, "Invalid quality for " & Item); else T.Assert (Quality = 1.0, "Invalid quality for " & Item); end if; Count := Count + 1; end Process_Text; begin Split_Header ("text/plain; q=0.5, text/html,text/x-dvi; q=0.8, text/x-c", Process_Text'Access); Util.Tests.Assert_Equals (T, 4, Count, "Invalid number of items"); end Test_Split_Header; -- ------------------------------ -- Test the Accept_Locales procedure. -- ------------------------------ procedure Test_Accept_Locales (T : in out Test) is procedure Process_Locale (Locale : in Util.Locales.Locale; Quality : in Quality_Type); use Util.Locales; Req : ASF.Requests.Mockup.Request; Count : Natural := 0; procedure Process_Locale (Locale : in Util.Locales.Locale; Quality : in Quality_Type) is pragma Unreferenced (Quality); Lang : constant String := Util.Locales.Get_Language (Locale); begin Log.Info ("Found locale: {0}", Util.Locales.To_String (Locale)); T.Assert (Lang = "da" or Lang = "en_GB" or Lang = "en", "Invalid lang: " & Lang); Count := Count + 1; end Process_Locale; begin Req.Set_Header ("Accept-Language", "da, en-gb;q=0.8, en;q=0.7"); Req.Accept_Locales (Process_Locale'Access); Util.Tests.Assert_Equals (T, 3, Count, "Invalid number of calls"); end Test_Accept_Locales; end ASF.Requests.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
954ac52a9c5214fd3802e9e0421e74550e6ec68c
src/sqlite/ado-drivers-connections-sqlite.ads
src/sqlite/ado-drivers-connections-sqlite.ads
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- 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 System; with Interfaces.C; package ADO.Drivers.Connections.Sqlite is subtype Sqlite_Access is System.Address; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; -- Check for an error after executing a sqlite statement. procedure Check_Error (Connection : in Sqlite_Access; Result : in Interfaces.C.int); private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased Sqlite_Access; Name : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); -- Releases the sqlite connection if it is open overriding procedure Finalize (Database : in out Database_Connection); procedure Execute (Database : in out Database_Connection; SQL : in Query_String); type Sqlite_Driver is new ADO.Drivers.Connections.Driver with null record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; with Interfaces.C; package ADO.Drivers.Connections.Sqlite is subtype Sqlite3 is Sqlite3_H.sqlite3; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; -- Check for an error after executing a sqlite statement. procedure Check_Error (Connection : access Sqlite3; Result : in Interfaces.C.int); private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); -- Releases the sqlite connection if it is open overriding procedure Finalize (Database : in out Database_Connection); procedure Execute (Database : in out Database_Connection; SQL : in Query_String); type Sqlite_Driver is new ADO.Drivers.Connections.Driver with null record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); end ADO.Drivers.Connections.Sqlite;
Replace Sqlite_Access and System.Address with the access Sqlite3 type
Replace Sqlite_Access and System.Address with the access Sqlite3 type
Ada
apache-2.0
stcarrez/ada-ado
d0858f0f166b466bbf3b9e30d906e855406e75e8
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; package body ADO.Drivers.Connections is use Util.Log; use Ada.Strings.Fixed; Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers.Connections"); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 > Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); Controller.Port := Integer'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Integer is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- 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); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin Log.Info ("Get driver {0}", Name); while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Util.Log; use Ada.Strings.Fixed; Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers.Connections"); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 > Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); Controller.Port := Integer'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Integer is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- 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); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; type Driver_Initialize_Access is not null access procedure; procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", 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 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.Info ("Get driver {0}", Name); for Retry in 0 .. 1 loop if Retry > 0 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
Add support to load database drivers dynamically - extract the driver name from the connection string, - load the DLL, - find the driver initialization method and call it
Add support to load database drivers dynamically - extract the driver name from the connection string, - load the DLL, - find the driver initialization method and call it
Ada
apache-2.0
stcarrez/ada-ado
02f255219d9feb47ac2ac056372f6c05d66be6d5
awa/src/awa-users-principals.ads
awa/src/awa-users-principals.ads
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with AWA.Users.Models; with ASF.Principals; with Security.Permissions; package AWA.Users.Principals is type Principal is new ASF.Principals.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Security.Permissions.Role_Type) return Boolean; -- Get the principal identifier (name) function Get_Id (From : in Principal) return String; -- Get the user associated with the principal. function Get_User (From : in Principal) return AWA.Users.Models.User_Ref; -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. function Get_User_Identifier (From : in Principal) return ADO.Identifier; -- Get the connection session used by the user. function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref; -- Get the connection session identifier used by the user. function Get_Session_Identifier (From : in Principal) return ADO.Identifier; -- Create a principal for the given user. function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal_Access; -- Utility functions based on the security principal access type. -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal. function Get_User_Identifier (From : in Security.Permissions.Principal_Access) return ADO.Identifier; private type Principal is new ASF.Principals.Principal with record User : AWA.Users.Models.User_Ref; Session : AWA.Users.Models.Session_Ref; Roles : Security.Permissions.Role_Map; end record; end AWA.Users.Principals;
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with AWA.Users.Models; with ASF.Principals; with Security.Permissions; package AWA.Users.Principals is type Principal is new ASF.Principals.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Security.Permissions.Role_Type) return Boolean; -- Get the principal identifier (name) function Get_Id (From : in Principal) return String; -- Get the user associated with the principal. function Get_User (From : in Principal) return AWA.Users.Models.User_Ref; -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. function Get_User_Identifier (From : in Principal) return ADO.Identifier; -- Get the connection session used by the user. function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref; -- Get the connection session identifier used by the user. function Get_Session_Identifier (From : in Principal) return ADO.Identifier; -- Create a principal for the given user. function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal_Access; -- Utility functions based on the security principal access type. -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal. function Get_User_Identifier (From : in ASF.Principals.Principal_Access) return ADO.Identifier; private type Principal is new ASF.Principals.Principal with record User : AWA.Users.Models.User_Ref; Session : AWA.Users.Models.Session_Ref; Roles : Security.Permissions.Role_Map; end record; end AWA.Users.Principals;
Use ASF Principal definitions
Use ASF Principal definitions
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
755f7debdf737e71122a23d18c7ca536c5686bf5
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; procedure Register_Servant (Adapter : in Manager; Proxy : in Reader_Access); -- Register the proxy servant in the object adapter. -- function Get_Manager (Refs : in ClientInfo_Ref_Map) return Manager; -- Return the object adapter manager which holds all the servant -- for the client. procedure Register_Message_Analyzer (Proxy : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Attribute_Table; Table : out MAT.Events.Attribute_Table_Ptr); -- Setup the servant to receive and process messages identified -- by Name. procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message); private type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Size : Natural; Total : Natural; 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.Attribute_Table_Ptr; 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 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 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.Attribute_Table_Ptr); procedure Register_Servant (Adapter : in Manager; Proxy : in Reader_Access); -- Register the proxy servant in the object adapter. -- function Get_Manager (Refs : in ClientInfo_Ref_Map) return Manager; -- Return the object adapter manager which holds all the servant -- for the client. procedure Register_Message_Analyzer (Proxy : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Attribute_Table; Table : out MAT.Events.Attribute_Table_Ptr); -- Setup the servant to receive and process messages identified -- by Name. procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message); private type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Size : Natural; Total : Natural; 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.Attribute_Table_Ptr; 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 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;
Define the Register_Reader operation
Define the Register_Reader operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c242cf8495b6d03f57f8b7f1a4fce7cce1e96343
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 -- ------------------------------ -- 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 := new Target_Process_Type; Process.Pid := Pid; end Create_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; -- ------------------------------ -- 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 := new Target_Process_Type; Process.Pid := Pid; end Create_Process; end MAT.Targets;
Implement the Console function to return the current console instance
Implement the Console function to return the current console instance
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
247c4660c99fa70e19b50c25c3908e07cd8977fc
src/util-streams-texts.ads
src/util-streams-texts.ads
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Util.Streams.Buffered; with Ada.Calendar; with GNAT.Calendar.Time_IO; package Util.Streams.Texts is -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is new Buffered.Output_Buffer_Stream with private; type Print_Stream_Access is access all Print_Stream'Class; procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access); -- Write a raw character on the stream. procedure Write (Stream : in out Print_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 Print_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer); -- Write a string on the stream. -- procedure Write (Stream : in out Print_Stream; -- Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a date on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date); -- Get the output stream content as a string. function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String; -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character); -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character); -- ----------------------- -- Reader stream -- ----------------------- -- The <b>Reader_Stream</b> is an input stream which provides helper methods -- for reading text streams. type Reader_Stream is new Buffered.Input_Buffer_Stream with private; type Reader_Stream_Access is access all Reader_Stream'Class; -- Initialize the reader to read the input from the input stream given in <b>From</b>. procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access); -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False); private type Print_Stream is new Buffered.Output_Buffer_Stream with null record; type Reader_Stream is new Buffered.Input_Buffer_Stream with null record; end Util.Streams.Texts;
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Util.Streams.Buffered; with Ada.Calendar; with GNAT.Calendar.Time_IO; package Util.Streams.Texts is -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is new Buffered.Output_Buffer_Stream with private; type Print_Stream_Access is access all Print_Stream'Class; procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access); -- Write a raw character on the stream. procedure Write (Stream : in out Print_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 Print_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer); -- Write a date on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date); -- Get the output stream content as a string. function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String; -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character); -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character); -- ----------------------- -- Reader stream -- ----------------------- -- The <b>Reader_Stream</b> is an input stream which provides helper methods -- for reading text streams. type Reader_Stream is new Buffered.Input_Buffer_Stream with private; type Reader_Stream_Access is access all Reader_Stream'Class; -- Initialize the reader to read the input from the input stream given in <b>From</b>. procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access); -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False); private type Print_Stream is new Buffered.Output_Buffer_Stream with null record; type Reader_Stream is new Buffered.Input_Buffer_Stream with null record; end Util.Streams.Texts;
Remove commented and unused Write procedure declaration
Remove commented and unused Write procedure declaration
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f1b27a1590890c638469e0059b637d0c05bb4351
src/babel-strategies-workers.adb
src/babel-strategies-workers.adb
----------------------------------------------------------------------- -- babel-strategies-workers -- Tasks that perform strategy work -- 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; package body Babel.Strategies.Workers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies.Workers"); procedure Start (Worker : in out Worker_Type; Strategy : in Babel.Strategies.Strategy_Type_Access) is begin for I in Worker.Workers'Range loop Worker.Workers (I).Start (Strategy); end loop; end Start; task body Worker_Task is S : Babel.Strategies.Strategy_Type_Access; begin Log.Info ("Strategy worker is started"); select accept Start (Strategy : in Babel.Strategies.Strategy_Type_Access) do S := Strategy; end Start; or terminate; end select; loop begin S.Execute; exception when Babel.Files.File_Fifo.Timeout => Log.Info ("Strategy worker stopped on timeout"); exit; when E : others => Log.Error ("Strategy worker received exception", E); end; end loop; end Worker_Task; end Babel.Strategies.Workers;
----------------------------------------------------------------------- -- babel-strategies-workers -- Tasks that perform strategy work -- 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; package body Babel.Strategies.Workers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies.Workers"); procedure Start (Worker : in out Worker_Type; Strategy : in Babel.Strategies.Strategy_Type_Access) is begin for I in Worker.Workers'Range loop Worker.Workers (I).Start (Strategy); end loop; end Start; task body Worker_Task is S : Babel.Strategies.Strategy_Type_Access; begin Log.Info ("Strategy worker is started"); select accept Start (Strategy : in Babel.Strategies.Strategy_Type_Access) do S := Strategy; end Start; or terminate; end select; loop begin S.Execute; exception when Babel.Files.Queues.File_Fifo.Timeout => Log.Info ("Strategy worker stopped on timeout"); exit; when E : others => Log.Error ("Strategy worker received exception", E); end; end loop; end Worker_Task; end Babel.Strategies.Workers;
Fix compilation after code refactoring
Fix compilation after code refactoring
Ada
apache-2.0
stcarrez/babel
498789e1771d16de4110eaa8108d7e38ecf90933
awa/plugins/awa-images/src/awa-images.ads
awa/plugins/awa-images/src/awa-images.ads
----------------------------------------------------------------------- -- awa-images -- Image module -- 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. ----------------------------------------------------------------------- -- == Introduction == -- -- @include awa-images-modules.ads -- @include awa-images-services.ads -- @include awa-images-beans.ads -- @include images.xml -- @include image-list.xml -- -- == Model == -- [images/awa_images_model.png] -- package AWA.Images is end AWA.Images;
----------------------------------------------------------------------- -- awa-images -- Image module -- 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. ----------------------------------------------------------------------- -- == Introduction == -- The image plugin is an extension to the storage plugin that identifies images and -- provides thumbnails as well as resizing of the original image. -- -- @include awa-images-modules.ads -- @include awa-images-beans.ads -- @include image-list.xml -- -- == Model == -- [images/awa_images_model.png] -- package AWA.Images is end AWA.Images;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
fa6a318699433a585523fe1ec24169a1de1e889e
src/asf-applications-messages-factory.adb
src/asf-applications-messages-factory.adb
----------------------------------------------------------------------- -- applications.messages-factory -- Application Message Factory -- 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.Exceptions; with Util.Log.Loggers; with Util.Properties.Bundles; with Util.Beans.Objects; with ASF.Locales; with ASF.Applications.Main; package body ASF.Applications.Messages.Factory is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Messages.Factory"); -- ------------------------------ -- Get a localized message. The message identifier is composed of a resource bundle name -- prefix and a bundle key. The prefix and key are separated by the first '.'. -- If the message identifier does not contain any prefix, the default bundle is "messages". -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String) return String is Pos : constant Natural := Util.Strings.Index (Message_Id, '.'); App : constant access ASF.Applications.Main.Application'Class := Context.Get_Application; Bundle : ASF.Locales.Bundle; begin if Pos > 0 then App.Load_Bundle (Name => Message_Id (Message_Id'First .. Pos - 1), Locale => "en", Bundle => Bundle); return Bundle.Get (Message_Id (Pos + 1 .. Message_Id'Last), Message_Id (Pos + 1 .. Message_Id'Last)); else App.Load_Bundle (Name => "messages", Locale => "en", Bundle => Bundle); return Bundle.Get (Message_Id, Message_Id); end if; exception when E : Util.Properties.Bundles.NO_BUNDLE => Log.Error ("Cannot localize {0}: {1}", Message_Id, Ada.Exceptions.Exception_Message (E)); return Message_Id; end Get_Message; -- ------------------------------ -- Build a localized message. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Severity : in Messages.Severity := ERROR) return Message is Msg : constant String := Get_Message (Context, Message_Id); Result : Message; begin Result.Summary := Ada.Strings.Unbounded.To_Unbounded_String (Msg); Result.Kind := Severity; return Result; end Get_Message; -- ------------------------------ -- Build a localized message and format the message with one argument. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Severity : in Messages.Severity := ERROR) return Message is Args : ASF.Utils.Object_Array (1 .. 1); begin Args (1) := Util.Beans.Objects.To_Object (Param1); return Get_Message (Context, Message_Id, Args, Severity); end Get_Message; -- ------------------------------ -- Build a localized message and format the message with two argument. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Param2 : in String; Severity : in Messages.Severity := ERROR) return Message is Args : ASF.Utils.Object_Array (1 .. 2); begin Args (1) := Util.Beans.Objects.To_Object (Param1); Args (2) := Util.Beans.Objects.To_Object (Param2); return Get_Message (Context, Message_Id, Args, Severity); end Get_Message; -- ------------------------------ -- Build a localized message and format the message with some arguments. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Args : in ASF.Utils.Object_Array; Severity : in Messages.Severity := ERROR) return Message is Msg : constant String := Get_Message (Context, Message_Id); Result : Message; begin Result.Kind := Severity; ASF.Utils.Formats.Format (Msg, Args, Result.Summary); return Result; end Get_Message; -- ------------------------------ -- Add a localized global message in the faces context. -- ------------------------------ procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Severity : in Messages.Severity := ERROR) is Msg : constant Message := Get_Message (Context, Message_Id, Param1, Severity); begin Context.Add_Message (Client_Id => "", Message => Msg); end Add_Message; -- ------------------------------ -- Add a localized global message in the faces context. -- ------------------------------ procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Severity : in Messages.Severity := ERROR) is Msg : constant Message := Get_Message (Context, Message_Id, Severity); begin Context.Add_Message (Client_Id => "", Message => Msg); end Add_Message; -- ------------------------------ -- Add a localized global message in the current faces context. -- ------------------------------ procedure Add_Message (Message_Id : in String; Severity : in Messages.Severity := ERROR) is Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin Add_Message (Context.all, Message_Id, Severity); end Add_Message; end ASF.Applications.Messages.Factory;
----------------------------------------------------------------------- -- applications.messages-factory -- Application Message Factory -- 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.Exceptions; with Util.Log.Loggers; with Util.Properties.Bundles; with Util.Beans.Objects; with Util.Locales; with ASF.Locales; with ASF.Applications.Main; package body ASF.Applications.Messages.Factory is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Messages.Factory"); -- ------------------------------ -- Get a localized message. The message identifier is composed of a resource bundle name -- prefix and a bundle key. The prefix and key are separated by the first '.'. -- If the message identifier does not contain any prefix, the default bundle is "messages". -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String) return String is Pos : constant Natural := Util.Strings.Index (Message_Id, '.'); Locale : constant Util.Locales.Locale := Context.Get_Locale; App : constant access ASF.Applications.Main.Application'Class := Context.Get_Application; Bundle : ASF.Locales.Bundle; begin if Pos > 0 then App.Load_Bundle (Name => Message_Id (Message_Id'First .. Pos - 1), Locale => Util.Locales.To_String (Locale), Bundle => Bundle); return Bundle.Get (Message_Id (Pos + 1 .. Message_Id'Last), Message_Id (Pos + 1 .. Message_Id'Last)); else App.Load_Bundle (Name => "messages", Locale => Util.Locales.To_String (Locale), Bundle => Bundle); return Bundle.Get (Message_Id, Message_Id); end if; exception when E : Util.Properties.Bundles.NO_BUNDLE => Log.Error ("Cannot localize {0}: {1}", Message_Id, Ada.Exceptions.Exception_Message (E)); return Message_Id; end Get_Message; -- ------------------------------ -- Build a localized message. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Severity : in Messages.Severity := ERROR) return Message is Msg : constant String := Get_Message (Context, Message_Id); Result : Message; begin Result.Summary := Ada.Strings.Unbounded.To_Unbounded_String (Msg); Result.Kind := Severity; return Result; end Get_Message; -- ------------------------------ -- Build a localized message and format the message with one argument. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Severity : in Messages.Severity := ERROR) return Message is Args : ASF.Utils.Object_Array (1 .. 1); begin Args (1) := Util.Beans.Objects.To_Object (Param1); return Get_Message (Context, Message_Id, Args, Severity); end Get_Message; -- ------------------------------ -- Build a localized message and format the message with two argument. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Param2 : in String; Severity : in Messages.Severity := ERROR) return Message is Args : ASF.Utils.Object_Array (1 .. 2); begin Args (1) := Util.Beans.Objects.To_Object (Param1); Args (2) := Util.Beans.Objects.To_Object (Param2); return Get_Message (Context, Message_Id, Args, Severity); end Get_Message; -- ------------------------------ -- Build a localized message and format the message with some arguments. -- ------------------------------ function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Args : in ASF.Utils.Object_Array; Severity : in Messages.Severity := ERROR) return Message is Msg : constant String := Get_Message (Context, Message_Id); Result : Message; begin Result.Kind := Severity; ASF.Utils.Formats.Format (Msg, Args, Result.Summary); return Result; end Get_Message; -- ------------------------------ -- Add a localized global message in the faces context. -- ------------------------------ procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Param1 : in String; Severity : in Messages.Severity := ERROR) is Msg : constant Message := Get_Message (Context, Message_Id, Param1, Severity); begin Context.Add_Message (Client_Id => "", Message => Msg); end Add_Message; -- ------------------------------ -- Add a localized global message in the faces context. -- ------------------------------ procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class; Message_Id : in String; Severity : in Messages.Severity := ERROR) is Msg : constant Message := Get_Message (Context, Message_Id, Severity); begin Context.Add_Message (Client_Id => "", Message => Msg); end Add_Message; -- ------------------------------ -- Add a localized global message in the current faces context. -- ------------------------------ procedure Add_Message (Message_Id : in String; Severity : in Messages.Severity := ERROR) is Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin Add_Message (Context.all, Message_Id, Severity); end Add_Message; end ASF.Applications.Messages.Factory;
Use the context locale to localize the message
Use the context locale to localize the message
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8a6d14e57d7e920301f9b278a00fad638f8cf402
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 Util.Streams.Buffered; with MAT.Types; with MAT.Events; with MAT.Events.Targets; 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; Frame : in MAT.Events.Frame_Info; Msg : in out Message) is abstract; ----------------- -- 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 abstract 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); -- Read a message from the stream. procedure Read_Message (Client : in out Manager_Base; Msg : in out Message) is abstract; -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (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; Buffer : Util.Streams.Buffered.Buffer_Access; 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 abstract tagged limited record Readers : Reader_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; end record; -- Read 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 Util.Streams.Buffered; with MAT.Types; with MAT.Events; with MAT.Events.Targets; 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; Frame : in MAT.Events.Frame_Info; Msg : in out Message) is abstract; ----------------- -- 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 abstract 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); -- Read a message from the stream. procedure Read_Message (Client : in out Manager_Base; Msg : in out Message) is abstract; -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Manager_Base; Msg : in out Message); -- Set the target events. procedure Set_Target_Events (Client : in out Manager_Base; Events : out MAT.Events.Targets.Target_Events_Access); 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; 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 abstract tagged limited record Readers : Reader_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : aliased MAT.Events.Targets.Target_Events; 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;
Declare the Set_Target_Events procedure
Declare the Set_Target_Events procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ad48aec2f863b863c44c8c185a09e4002adec23f
awa/src/awa-events-queues-persistents.adb
awa/src/awa-events-queues-persistents.adb
----------------------------------------------------------------------- -- awa-events-queues-persistents -- AWA Event Queues -- Copyright (C) 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.Calendar; with Util.Log.Loggers; with Util.Serialize.Tools; with AWA.Services.Contexts; with AWA.Applications; with AWA.Events.Services; with AWA.Users.Models; with ADO; with ADO.Sessions; with ADO.SQL; package body AWA.Events.Queues.Persistents is package AC renames AWA.Services.Contexts; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents"); -- ------------------------------ -- Get the queue name. -- ------------------------------ overriding function Get_Name (From : in Persistent_Queue) return String is begin return From.Name; end Get_Name; -- ------------------------------ -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. -- ------------------------------ overriding function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is begin return From.Queue; end Get_Queue; -- ------------------------------ -- Queue the event. The event is saved in the database with a relation to -- the user, the user session, the event queue and the event type. -- ------------------------------ overriding procedure Enqueue (Into : in out Persistent_Queue; Event : in AWA.Events.Module_Event'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant AC.Service_Context_Access := AC.Current; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Event.Get_Event_Kind); end Set_Event; begin App.Do_Event_Manager (Set_Event'Access); Ctx.Start; Msg.Set_Queue (Into.Queue); Msg.Set_User (Ctx.Get_User); Msg.Set_Session (Ctx.Get_User_Session); Msg.Set_Create_Date (Event.Get_Time); Msg.Set_Status (AWA.Events.Models.QUEUED); Msg.Set_Entity_Id (Event.Get_Entity_Identifier); Msg.Set_Entity_Type (Event.Entity_Type); -- Collect the event parameters in a string and format the result in JSON. Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Event.Props)); Msg.Save (DB); Ctx.Commit; Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id)); end Enqueue; overriding procedure Dequeue (From : in out Persistent_Queue; Process : access procedure (Event : in Module_Event'Class)) is -- Prepare the message by indicating in the database it is going to be processed -- by the given server and task. procedure Prepare_Message (Msg : in out Models.Message_Ref); -- Dispatch the event. procedure Dispatch_Message (Msg : in out Models.Message_Ref); -- Finish processing the message by marking it as being processed. procedure Finish_Message (Msg : in out Models.Message_Ref); Ctx : constant AC.Service_Context_Access := AC.Current; DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx); Messages : Models.Message_Vector; Query : ADO.SQL.Query; Task_Id : constant Integer := 0; -- ------------------------------ -- Prepare the message by indicating in the database it is going to be processed -- by the given server and task. -- ------------------------------ procedure Prepare_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSING); Msg.Set_Server_Id (From.Server_Id); Msg.Set_Task_Id (Task_Id); Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Prepare_Message; -- Dispatch the event. procedure Dispatch_Message (Msg : in out Models.Message_Ref) is User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User; Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session; Name : constant String := Msg.Get_Message_Type.Get_Name; Event : Module_Event; procedure Action; procedure Action is begin Process (Event); end Action; procedure Run is new AWA.Services.Contexts.Run_As (Action); begin Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Name)); Util.Serialize.Tools.From_JSON (Msg.Get_Parameters, Event.Props); Event.Set_Entity_Identifier (Msg.Get_Entity_Id); Event.Entity_Type := Msg.Get_Entity_Type; Log.Info ("Dispatching event 0} for user{1} session{2}", Name, ADO.Identifier'Image (User.Get_Id), ADO.Identifier'Image (Session.Get_Id)); -- Run the Process action on behalf of the user associated with the message. Run (AWA.Users.Models.User_Ref (User), AWA.Users.Models.Session_Ref (Session)); exception when E : others => Log.Error ("Exception when processing event " & Name, E, True); end Dispatch_Message; -- ------------------------------ -- Finish processing the message by marking it as being processed. -- ------------------------------ procedure Finish_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSED); Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Finish_Message; Count : Natural; begin Ctx.Start; Query.Set_Filter ("o.status = 0 AND o.queue_id = :queue ORDER BY o.priority DESC, " & "o.id ASC LIMIT :max"); Query.Bind_Param ("queue", From.Queue.Get_Id); Query.Bind_Param ("max", From.Max_Batch); Models.List (Messages, DB, Query); Count := Natural (Messages.Length); -- Prepare the event messages by marking them in the database. -- This makes sure that no other server or task (if any), will process them. if Count > 0 then for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Prepare_Message'Access); end loop; end if; Ctx.Commit; if Count = 0 then return; end if; Log.Info ("Dispatching {0} events", Natural'Image (Count)); -- Dispatch each event. for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Dispatch_Message'Access); end loop; -- After having dispatched the events, mark them as dispatched in the queue. Ctx.Start; for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Finish_Message'Access); end loop; Ctx.Commit; end Dequeue; -- ------------------------------ -- Create the queue associated with the given name and configure it by using -- the configuration properties. -- ------------------------------ function Create_Queue (Name : in String; Props : in EL.Beans.Param_Vectors.Vector; Context : in EL.Contexts.ELContext'Class) return Queue_Access is pragma Unreferenced (Props, Context); package AC renames AWA.Services.Contexts; Ctx : constant AC.Service_Context_Access := AC.Current; Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx); Queue : AWA.Events.Models.Queue_Ref; Query : ADO.SQL.Query; Found : Boolean; begin Session.Begin_Transaction; -- Find the queue instance which matches the name. Query.Set_Filter ("o.name = ?"); Query.Add_Param (Name); Queue.Find (Session => Session, Query => Query, Found => Found); -- But create the queue instance if it does not exist. if not Found then Log.Info ("Creating database queue {0}", Name); Queue.Set_Name (Name); Queue.Save (Session); else Log.Info ("Using database queue {0}", Name); end if; Session.Commit; return new Persistent_Queue '(Name_Length => Name'Length, Name => Name, Queue => Queue, others => <>); end Create_Queue; end AWA.Events.Queues.Persistents;
----------------------------------------------------------------------- -- awa-events-queues-persistents -- AWA Event Queues -- Copyright (C) 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.Calendar; with Util.Log.Loggers; with Util.Serialize.Tools; with AWA.Services.Contexts; with AWA.Applications; with AWA.Events.Services; with AWA.Users.Models; with ADO; with ADO.Sessions; with ADO.SQL; package body AWA.Events.Queues.Persistents is package AC renames AWA.Services.Contexts; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents"); -- ------------------------------ -- Get the queue name. -- ------------------------------ overriding function Get_Name (From : in Persistent_Queue) return String is begin return From.Name; end Get_Name; -- ------------------------------ -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. -- ------------------------------ overriding function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is begin return From.Queue; end Get_Queue; -- ------------------------------ -- Queue the event. The event is saved in the database with a relation to -- the user, the user session, the event queue and the event type. -- ------------------------------ overriding procedure Enqueue (Into : in out Persistent_Queue; Event : in AWA.Events.Module_Event'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant AC.Service_Context_Access := AC.Current; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Event.Get_Event_Kind); end Set_Event; begin App.Do_Event_Manager (Set_Event'Access); Ctx.Start; Msg.Set_Queue (Into.Queue); Msg.Set_User (Ctx.Get_User); Msg.Set_Session (Ctx.Get_User_Session); Msg.Set_Create_Date (Event.Get_Time); Msg.Set_Status (AWA.Events.Models.QUEUED); Msg.Set_Entity_Id (Event.Get_Entity_Identifier); Msg.Set_Entity_Type (Event.Entity_Type); -- Collect the event parameters in a string and format the result in JSON. Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Event.Props)); Msg.Save (DB); Ctx.Commit; Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id)); end Enqueue; overriding procedure Dequeue (From : in out Persistent_Queue; Process : access procedure (Event : in Module_Event'Class)) is -- Prepare the message by indicating in the database it is going to be processed -- by the given server and task. procedure Prepare_Message (Msg : in out Models.Message_Ref); -- Dispatch the event. procedure Dispatch_Message (Msg : in out Models.Message_Ref); -- Finish processing the message by marking it as being processed. procedure Finish_Message (Msg : in out Models.Message_Ref); Ctx : constant AC.Service_Context_Access := AC.Current; DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx); Messages : Models.Message_Vector; Query : ADO.SQL.Query; Task_Id : constant Integer := 0; -- ------------------------------ -- Prepare the message by indicating in the database it is going to be processed -- by the given server and task. -- ------------------------------ procedure Prepare_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSING); Msg.Set_Server_Id (From.Server_Id); Msg.Set_Task_Id (Task_Id); Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Prepare_Message; -- Dispatch the event. procedure Dispatch_Message (Msg : in out Models.Message_Ref) is User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User; Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session; Name : constant String := Msg.Get_Message_Type.Get_Name; Event : Module_Event; procedure Action; procedure Action is begin Process (Event); end Action; procedure Run is new AWA.Services.Contexts.Run_As (Action); begin Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Name)); Util.Serialize.Tools.From_JSON (Msg.Get_Parameters, Event.Props); Event.Set_Entity_Identifier (Msg.Get_Entity_Id); Event.Entity_Type := Msg.Get_Entity_Type; if not User.Is_Null then Log.Info ("Dispatching event {0} for user{1} session{2}", Name, ADO.Identifier'Image (User.Get_Id), ADO.Identifier'Image (Session.Get_Id)); else Log.Info ("Dispatching event {0}", Name); end if; -- Run the Process action on behalf of the user associated with the message. Run (AWA.Users.Models.User_Ref (User), AWA.Users.Models.Session_Ref (Session)); exception when E : others => Log.Error ("Exception when processing event " & Name, E, True); end Dispatch_Message; -- ------------------------------ -- Finish processing the message by marking it as being processed. -- ------------------------------ procedure Finish_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSED); Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Finish_Message; Count : Natural; begin Ctx.Start; Query.Set_Filter ("o.status = 0 AND o.queue_id = :queue ORDER BY o.priority DESC, " & "o.id ASC LIMIT :max"); Query.Bind_Param ("queue", From.Queue.Get_Id); Query.Bind_Param ("max", From.Max_Batch); Models.List (Messages, DB, Query); Count := Natural (Messages.Length); -- Prepare the event messages by marking them in the database. -- This makes sure that no other server or task (if any), will process them. if Count > 0 then for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Prepare_Message'Access); end loop; end if; Ctx.Commit; if Count = 0 then return; end if; Log.Info ("Dispatching {0} events", Natural'Image (Count)); -- Dispatch each event. for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Dispatch_Message'Access); end loop; -- After having dispatched the events, mark them as dispatched in the queue. Ctx.Start; for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Finish_Message'Access); end loop; Ctx.Commit; end Dequeue; -- ------------------------------ -- Create the queue associated with the given name and configure it by using -- the configuration properties. -- ------------------------------ function Create_Queue (Name : in String; Props : in EL.Beans.Param_Vectors.Vector; Context : in EL.Contexts.ELContext'Class) return Queue_Access is pragma Unreferenced (Props, Context); package AC renames AWA.Services.Contexts; Ctx : constant AC.Service_Context_Access := AC.Current; Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx); Queue : AWA.Events.Models.Queue_Ref; Query : ADO.SQL.Query; Found : Boolean; begin Session.Begin_Transaction; -- Find the queue instance which matches the name. Query.Set_Filter ("o.name = ?"); Query.Add_Param (Name); Queue.Find (Session => Session, Query => Query, Found => Found); -- But create the queue instance if it does not exist. if not Found then Log.Info ("Creating database queue {0}", Name); Queue.Set_Name (Name); Queue.Save (Session); else Log.Info ("Using database queue {0}", Name); end if; Session.Commit; return new Persistent_Queue '(Name_Length => Name'Length, Name => Name, Queue => Queue, others => <>); end Create_Queue; end AWA.Events.Queues.Persistents;
Fix the crash that could occur when a job not associated with a user is executed
Fix the crash that could occur when a job not associated with a user is executed
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f32dd9a904a6286034492e6878b741ef6b9c6596
samples/beans/users.adb
samples/beans/users.adb
----------------------------------------------------------------------- -- users - Gives access to the OpenID principal through an Ada bean -- 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 ASF.Contexts.Faces; with ASF.Contexts.Flash; with ASF.Sessions; with ASF.Principals; with ASF.Cookies; with ASF.Events.Faces.Actions; with ASF.Applications.Messages.Factory; with GNAT.MD5; with Security.OpenID; with ASF.Security.Filters; with Util.Strings.Transforms; package body Users is use Ada.Strings.Unbounded; use Security.OpenID; use type ASF.Principals.Principal_Access; use type ASF.Contexts.Faces.Faces_Context_Access; procedure Remove_Cookie (Name : in String); -- ------------------------------ -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) -- ------------------------------ function Get_Gravatar_Link (Email : in String) return String is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin return "http://www.gravatar.com/avatar/" & C; end Get_Gravatar_Link; -- ------------------------------ -- Get the user information identified by the given name. -- ------------------------------ function Get_Value (From : in User_Info; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session; P : ASF.Principals.Principal_Access := null; U : Security.OpenID.Principal_Access := null; begin if F /= null then S := F.Get_Session; if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.OpenID.Principal'Class (P.all)'Access; end if; end if; end if; if Name = "authenticated" then return Util.Beans.Objects.To_Object (U /= null); end if; if U = null then return Util.Beans.Objects.Null_Object; end if; if Name = "email" then return Util.Beans.Objects.To_Object (U.Get_Email); end if; if Name = "language" then return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication)); end if; if Name = "first_name" then return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication)); end if; if Name = "last_name" then return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication)); end if; if Name = "full_name" then return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication)); end if; if Name = "id" then return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication)); end if; if Name = "country" then return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication)); end if; if Name = "sessionId" then return Util.Beans.Objects.To_Object (S.Get_Id); end if; if Name = "gravatar" then return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email)); end if; return Util.Beans.Objects.To_Object (U.Get_Name); end Get_Value; -- ------------------------------ -- Helper to send a remove cookie in the current response -- ------------------------------ procedure Remove_Cookie (Name : in String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, ""); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 0); Ctx.Get_Response.Add_Cookie (Cookie => C); end Remove_Cookie; -- ------------------------------ -- Logout by dropping the user session. -- ------------------------------ procedure Logout (From : in out User_Info; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session := F.Get_Session; P : ASF.Principals.Principal_Access := null; U : Security.OpenID.Principal_Access := null; begin if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.OpenID.Principal'Class (P.all)'Access; end if; S.Invalidate; end if; if U /= null then F.Get_Flash.Set_Keep_Messages (True); ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message", Get_Full_Name (U.Get_Authentication)); end if; Remove_Cookie (ASF.Security.Filters.SID_COOKIE); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success"); end Logout; package Logout_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info, Method => Logout, Name => "logout"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Logout_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in User_Info) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; end Users;
----------------------------------------------------------------------- -- users - Gives access to the OpenID principal through an Ada bean -- 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 ASF.Contexts.Faces; with ASF.Contexts.Flash; with ASF.Sessions; with ASF.Principals; with ASF.Cookies; with ASF.Events.Faces.Actions; with ASF.Applications.Messages.Factory; with GNAT.MD5; with Security.Auth; with ASF.Security.Filters; with Util.Strings.Transforms; package body Users is use Ada.Strings.Unbounded; use Security.Auth; use type ASF.Principals.Principal_Access; use type ASF.Contexts.Faces.Faces_Context_Access; procedure Remove_Cookie (Name : in String); -- ------------------------------ -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) -- ------------------------------ function Get_Gravatar_Link (Email : in String) return String is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin return "http://www.gravatar.com/avatar/" & C; end Get_Gravatar_Link; -- ------------------------------ -- Get the user information identified by the given name. -- ------------------------------ function Get_Value (From : in User_Info; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session; P : ASF.Principals.Principal_Access := null; U : Security.Auth.Principal_Access := null; begin if F /= null then S := F.Get_Session; if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.Auth.Principal'Class (P.all)'Access; end if; end if; end if; if Name = "authenticated" then return Util.Beans.Objects.To_Object (U /= null); end if; if U = null then return Util.Beans.Objects.Null_Object; end if; if Name = "email" then return Util.Beans.Objects.To_Object (U.Get_Email); end if; if Name = "language" then return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication)); end if; if Name = "first_name" then return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication)); end if; if Name = "last_name" then return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication)); end if; if Name = "full_name" then return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication)); end if; if Name = "id" then return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication)); end if; if Name = "country" then return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication)); end if; if Name = "sessionId" then return Util.Beans.Objects.To_Object (S.Get_Id); end if; if Name = "gravatar" then return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email)); end if; return Util.Beans.Objects.To_Object (U.Get_Name); end Get_Value; -- ------------------------------ -- Helper to send a remove cookie in the current response -- ------------------------------ procedure Remove_Cookie (Name : in String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, ""); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 0); Ctx.Get_Response.Add_Cookie (Cookie => C); end Remove_Cookie; -- ------------------------------ -- Logout by dropping the user session. -- ------------------------------ procedure Logout (From : in out User_Info; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session := F.Get_Session; P : ASF.Principals.Principal_Access := null; U : Security.Auth.Principal_Access := null; begin if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.Auth.Principal'Class (P.all)'Access; end if; S.Invalidate; end if; if U /= null then F.Get_Flash.Set_Keep_Messages (True); ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message", Get_Full_Name (U.Get_Authentication)); end if; Remove_Cookie (ASF.Security.Filters.SID_COOKIE); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success"); end Logout; package Logout_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info, Method => Logout, Name => "logout"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Logout_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in User_Info) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; end Users;
Use the Security.Auth implementation
Use the Security.Auth implementation
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
03dff0b9365f455e4cd2efe5e9b7f779467bcf3e
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; elsif Input_Length mod 3 = 0 then declare Largest_Run : constant Positive := 64 * 3; 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) + 2) + Tools.Image_Length (Last_Run_Size) + 2; end; elsif Input_Length mod 3 = 1 then declare Largest_Final_Run : constant Positive := 15 * 3 + 1; Largest_Prefix_Run : constant Positive := 64 * 3; Prefix_Run_Count : constant Natural := (Input_Length + Largest_Prefix_Run - Largest_Final_Run) / Largest_Prefix_Run; Last_Run_Size : constant Positive := Input_Length - Prefix_Run_Count * Largest_Prefix_Run; begin return Ada.Streams.Stream_Element_Count (Prefix_Run_Count) * (Tools.Image_Length (Largest_Prefix_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 1; end; elsif Input_Length mod 3 = 2 then declare Largest_Final_Run : constant Positive := ((62 - Natural (Last_Code)) * 4 - 1) * 3 + 2; Largest_Prefix_Run : constant Positive := 64 * 3; Prefix_Run_Count : constant Natural := (Input_Length + Largest_Prefix_Run - Largest_Final_Run) / Largest_Prefix_Run; Last_Run_Size : constant Positive := Input_Length - Prefix_Run_Count * Largest_Prefix_Run; begin return Ada.Streams.Stream_Element_Count (Prefix_Run_Count) * (Tools.Image_Length (Largest_Prefix_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 1; end; else raise Program_Error with "Condition unreachable"; 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 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;
fix multi-block verbatim size computation
smaz_implementations-base_64: fix multi-block verbatim size computation
Ada
isc
faelys/natools
a88d3f942244d2198fc24a2292689dd6e42c2902
src/gen-model-beans.adb
src/gen-model-beans.adb
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- 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 Gen.Model.Mappings; package body Gen.Model.Beans is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Bean_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isBean" then return Util.Beans.Objects.To_Object (True); else return Tables.Table_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Bean_Definition) is Iter : Gen.Model.Tables.Column_List.Cursor := O.Members.First; begin while Gen.Model.Tables.Column_List.Has_Element (Iter) loop Gen.Model.Tables.Column_List.Element (Iter).Prepare; Gen.Model.Tables.Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Bean_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create an attribute with the given name and add it to the bean. -- ------------------------------ procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access) is begin Column := new Gen.Model.Tables.Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Bean.Members.Get_Count; Column.Table := Bean'Unchecked_Access; Bean.Members.Append (Column); end Add_Attribute; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access is Bean : constant Bean_Definition_Access := new Bean_Definition; begin Bean.Kind := Mappings.T_BEAN; Bean.Name := Name; declare Pos : constant Natural := Index (Bean.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Bean.Pkg_Name := Unbounded_Slice (Bean.Name, 1, Pos - 1); Bean.Type_Name := Unbounded_Slice (Bean.Name, Pos + 1, Length (Bean.Name)); else Bean.Pkg_Name := To_Unbounded_String ("ADO"); Bean.Type_Name := Bean.Name; end if; end; return Bean; end Create_Bean; end Gen.Model.Beans;
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Gen.Model.Mappings; package body Gen.Model.Beans is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Bean_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isBean" then return Util.Beans.Objects.To_Object (True); else return Tables.Table_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Bean_Definition) is Iter : Gen.Model.Tables.Column_List.Cursor := O.Members.First; begin while Gen.Model.Tables.Column_List.Has_Element (Iter) loop Gen.Model.Tables.Column_List.Element (Iter).Prepare; Gen.Model.Tables.Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Create an attribute with the given name and add it to the bean. -- ------------------------------ procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access) is begin Column := new Gen.Model.Tables.Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Bean.Members.Get_Count; Column.Table := Bean'Unchecked_Access; Bean.Members.Append (Column); end Add_Attribute; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access is Bean : constant Bean_Definition_Access := new Bean_Definition; begin Bean.Kind := Mappings.T_BEAN; Bean.Name := Name; declare Pos : constant Natural := Index (Bean.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Bean.Pkg_Name := Unbounded_Slice (Bean.Name, 1, Pos - 1); Bean.Type_Name := Unbounded_Slice (Bean.Name, Pos + 1, Length (Bean.Name)); else Bean.Pkg_Name := To_Unbounded_String ("ADO"); Bean.Type_Name := Bean.Name; end if; end; return Bean; end Create_Bean; end Gen.Model.Beans;
Remove the Initialize operation
Remove the Initialize operation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
0f4a6afaeb08aea8c068effed6fe7d41b3159ca3
regtests/util-encoders-tests.ads
regtests/util-encoders-tests.ads
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in Util.Encoders.Encoder; D : in Util.Encoders.Decoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test HMAC-SHA256 procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_AES (T : in out Test); end Util.Encoders.Tests;
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in Util.Encoders.Encoder; D : in Util.Encoders.Decoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test HMAC-SHA256 procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_AES (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_Encrypt_Decrypt_Secret (T : in out Test); end Util.Encoders.Tests;
Declare Test_Encrypt_Decrypt_Secret procedure
Declare Test_Encrypt_Decrypt_Secret procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
50efa7dc421d876400858b34dc8ca4637547914e
src/wiki-attributes.adb
src/wiki-attributes.adb
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- 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.Characters.Conversions; with Ada.Unchecked_Deallocation; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Attr.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value; end Get_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List_Type; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Access := Attribute_Vectors.Element (Iter); begin if Attr.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String) is Attr : constant Attribute_Access := new Attribute '(Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attr); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name), Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List_Type) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List_Type) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List_Type) is procedure Free is new Ada.Unchecked_Deallocation (Object => Attribute, Name => Attribute_Access); Item : Attribute_Access; begin while not List.List.Is_Empty loop Item := List.List.Last_Element; List.List.Delete_Last; Free (Item); end loop; end Clear; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List_Type) is begin List.Clear; end Finalize; end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Ada.Unchecked_Deallocation; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Attr.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return To_Unbounded_Wide_Wide_String (Attr.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List_Type; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Access := Attribute_Vectors.Element (Iter); begin if Attr.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Unbounded_Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Null_Unbounded_Wide_Wide_String; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String) is Attr : constant Attribute_Access := new Attribute '(Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attr); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name), Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List_Type) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List_Type) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List_Type) is procedure Free is new Ada.Unchecked_Deallocation (Object => Attribute, Name => Attribute_Access); Item : Attribute_Access; begin while not List.List.Is_Empty loop Item := List.List.Last_Element; List.List.Delete_Last; Free (Item); end loop; end Clear; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List_Type) is begin List.Clear; end Finalize; end Wiki.Attributes;
Implement Get_Unbounded_Wide_Value function and Get_Attribute function
Implement Get_Unbounded_Wide_Value function and Get_Attribute function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
05c5bf835e3b361efce5b60c3b11a88c3995197a
mat/src/mat-formats.adb
mat/src/mat-formats.adb
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Formats is Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is use type MAT.Types.Target_Tick_Ref; T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Size (Item.Size) & " bytes allocated"; when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Size (Item.Size) & " bytes freed"; when others => return "unknown"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector) return String is Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First; Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated, " & Time (Free_Event.Time, Item.Time); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated"; end Event_Malloc; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Size (Item.Size) & " bytes freed"; when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; when others => return "unknown"; end case; end Event; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Size (Item.Size) & " bytes allocated"; when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Size (Item.Size) & " bytes freed"; when others => return "unknown"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector) return String is Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First; Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated, " & Duration (Free_Event.Time - Item.Time); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated"; end Event_Malloc; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Size (Item.Size) & " bytes freed"; when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; when others => return "unknown"; end case; end Event; end MAT.Formats;
Implement the Duration function
Implement the Duration function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c1b1a3cc7f88caf98b3ee1705e09ac3a598fdfdb
regtests/gen-artifacts-xmi-tests.adb
regtests/gen-artifacts-xmi-tests.adb
----------------------------------------------------------------------- -- gen-xmi-tests -- Tests for xmi -- Copyright (C) 2012, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Gen.Configs; with Gen.Generator; package body Gen.Artifacts.XMI.Tests is package Caller is new Util.Test_Caller (Test, "Gen.XMI"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration", Test_Read_XMI'Access); Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element", Test_Find_Element'Access); Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element", Test_Find_Tag_Definition'Access); end Add_Tests; -- ------------------------------ -- Test reading the XMI files defines in the Dynamo UML configuration repository. -- ------------------------------ procedure Test_Read_XMI (T : in out Test) is procedure Check (Namespace : in String; Name : in String; Id : in String); A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use type Gen.Model.XMI.Model_Element_Access; procedure Check (Namespace : in String; Name : in String; Id : in String) is Empty : Gen.Model.XMI.Model_Map.Map; XMI_Id : constant UString := To_UString (Namespace & "#" & Id); N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes, Empty, XMI_Id); begin T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id)); Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name"); end Check; begin Gen.Generator.Initialize (G, To_UString (C), False); A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", G); -- ArgoUML Integer DataType Check ("default-uml14.xmi", "Integer", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C"); -- ArgoUML String DataType Check ("default-uml14.xmi", "String", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E"); -- ArgoUML documentation TagDefinition Check ("default-uml14.xmi", "documentation", ".:000000000000087C"); -- ArgoUML type Stereotype Check ("default-uml14.xmi", "type", ".:0000000000000842"); -- Persistence Table Stereotype Check ("Dynamo.xmi", "Table", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F"); Check ("Dynamo.xmi", "PK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50"); Check ("Dynamo.xmi", "FK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70"); Check ("Dynamo.xmi", "Bean", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72"); end Test_Read_XMI; -- ------------------------------ -- Test searching an XMI element by using a qualified name. -- ------------------------------ procedure Test_Find_Element (T : in out Test) is A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use Gen.Model.XMI; function Find_Stereotype is new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element, Element_Type_Access => Stereotype_Element_Access); begin Gen.Generator.Initialize (G, To_UString (C), False); A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", G); declare S : Gen.Model.XMI.Stereotype_Element_Access; begin S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.PK", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.FK", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.DataModel", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "AWA.Bean", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); end; end Test_Find_Element; -- Test searching an XMI Tag definition element by using its name. procedure Test_Find_Tag_Definition (T : in out Test) is A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use Gen.Model.XMI; function Find_Tag_Definition is new Gen.Model.XMI.Find_Element (Element_Type => Tag_Definition_Element, Element_Type_Access => Tag_Definition_Element_Access); begin Gen.Generator.Initialize (G, To_UString (C), False); A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", G); declare Tag : Tag_Definition_Element_Access; begin Tag := Find_Tag_Definition (A.Nodes, "Dynamo.xmi", "[email protected]", Gen.Model.XMI.BY_NAME); T.Assert (Tag /= null, "Tag definition not found"); end; end Test_Find_Tag_Definition; end Gen.Artifacts.XMI.Tests;
----------------------------------------------------------------------- -- gen-xmi-tests -- Tests for xmi -- Copyright (C) 2012, 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.Test_Caller; with Gen.Configs; with Gen.Generator; package body Gen.Artifacts.XMI.Tests is package Caller is new Util.Test_Caller (Test, "Gen.XMI"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration", Test_Read_XMI'Access); Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element", Test_Find_Element'Access); Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element", Test_Find_Tag_Definition'Access); end Add_Tests; -- ------------------------------ -- Test reading the XMI files defines in the Dynamo UML configuration repository. -- ------------------------------ procedure Test_Read_XMI (T : in out Test) is procedure Check (Namespace : in String; Name : in String; Id : in String); A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use type Gen.Model.XMI.Model_Element_Access; procedure Check (Namespace : in String; Name : in String; Id : in String) is Empty : Gen.Model.XMI.Model_Map.Map; XMI_Id : constant UString := To_UString (Namespace & "#" & Id); N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes, Empty, XMI_Id); begin T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id)); Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name"); end Check; begin Gen.Generator.Initialize (G, To_UString (C), False); A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", "", G); -- ArgoUML Integer DataType Check ("default-uml14.xmi", "Integer", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C"); -- ArgoUML String DataType Check ("default-uml14.xmi", "String", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E"); -- ArgoUML documentation TagDefinition Check ("default-uml14.xmi", "documentation", ".:000000000000087C"); -- ArgoUML type Stereotype Check ("default-uml14.xmi", "type", ".:0000000000000842"); -- Persistence Table Stereotype Check ("Dynamo.xmi", "Table", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F"); Check ("Dynamo.xmi", "PK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50"); Check ("Dynamo.xmi", "FK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70"); Check ("Dynamo.xmi", "Bean", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72"); end Test_Read_XMI; -- ------------------------------ -- Test searching an XMI element by using a qualified name. -- ------------------------------ procedure Test_Find_Element (T : in out Test) is A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use Gen.Model.XMI; function Find_Stereotype is new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element, Element_Type_Access => Stereotype_Element_Access); begin Gen.Generator.Initialize (G, To_UString (C), False); A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", "", G); declare S : Gen.Model.XMI.Stereotype_Element_Access; begin S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.PK", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.FK", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.DataModel", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "AWA.Bean", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); end; end Test_Find_Element; -- Test searching an XMI Tag definition element by using its name. procedure Test_Find_Tag_Definition (T : in out Test) is A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use Gen.Model.XMI; function Find_Tag_Definition is new Gen.Model.XMI.Find_Element (Element_Type => Tag_Definition_Element, Element_Type_Access => Tag_Definition_Element_Access); begin Gen.Generator.Initialize (G, To_UString (C), False); A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", "", G); declare Tag : Tag_Definition_Element_Access; begin Tag := Find_Tag_Definition (A.Nodes, "Dynamo.xmi", "[email protected]", Gen.Model.XMI.BY_NAME); T.Assert (Tag /= null, "Tag definition not found"); end; end Test_Find_Tag_Definition; end Gen.Artifacts.XMI.Tests;
Update the unit test
Update the unit test
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
5b2bb9956abb8fb6d018c09c10c6ea8dea92077b
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "23"; copyright_years : constant String := "2015-2019"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.28"; default_pgsql : constant String := "10"; default_php : constant String := "7.2"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.3.0"; previous_compiler : constant String := "8.2.0"; binutils_version : constant String := "2.32"; previous_binutils : constant String := "2.31.1"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "24"; copyright_years : constant String := "2015-2019"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.28"; default_pgsql : constant String := "10"; default_php : constant String := "7.2"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.3.0"; previous_compiler : constant String := "8.2.0"; binutils_version : constant String := "2.32"; previous_binutils : constant String := "2.31.1"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
bump version
bump version
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
fecce32759ae690d9c2b30e0b3c37feae401a661
regtests/ado-tests.adb
regtests/ado-tests.adb
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; 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.Test_Caller; package body ADO.Tests is use Util.Log; use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Fail (T : in Test; Message : in String); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Fail (T : in Test; Message : in String) is begin T.Assert (False, Message); end Fail; procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; Fail (T, "Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; Fail (T, "Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE'Access); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use ADO.Objects; use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Unbounded_String; begin for I in 1 .. 127 loop Append (Name, Character'Val (I)); end loop; Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use ADO.Objects; use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : constant 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; end Test_Blob; 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); end Add_Tests; end ADO.Tests;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; 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.Test_Caller; package body ADO.Tests is use Util.Log; use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Fail (T : in Test; Message : in String); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Fail (T : in Test; Message : in String) is begin T.Assert (False, Message); end Fail; procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; Fail (T, "Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; Fail (T, "Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE'Access); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use ADO.Objects; use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Unbounded_String; begin for I in 1 .. 127 loop Append (Name, Character'Val (I)); end loop; Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use ADO.Objects; use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); end Test_Blob; 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); end Add_Tests; end ADO.Tests;
Update unit tests to check the blob
Update unit tests to check the blob
Ada
apache-2.0
stcarrez/ada-ado
1ca70f13d4130ef4d4dc62422efff9c45f67b754
src/asf-components-utils-scripts.adb
src/asf-components-utils-scripts.adb
----------------------------------------------------------------------- -- components-utils-scripts -- Javascript queue -- 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 ASF.Components.Utils.Scripts is -- ------------------------------ -- Write the content that was collected by rendering the inner children. -- Write the content in the Javascript queue. -- ------------------------------ overriding procedure Write_Content (UI : in UIScript; Writer : in out Contexts.Writer.Response_Writer'Class; Content : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI, Context); begin Writer.Queue_Script (Content); end Write_Content; end ASF.Components.Utils.Scripts;
----------------------------------------------------------------------- -- components-utils-scripts -- Javascript queue -- 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. ----------------------------------------------------------------------- package body ASF.Components.Utils.Scripts is -- ------------------------------ -- Write the content that was collected by rendering the inner children. -- Write the content in the Javascript queue. -- ------------------------------ overriding procedure Write_Content (UI : in UIScript; Writer : in out Contexts.Writer.Response_Writer'Class; Content : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI, Context); begin Writer.Queue_Script (Content); end Write_Content; -- ------------------------------ -- If the component provides a src attribute, render the <script src='xxx'></script> -- tag with an optional async attribute. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIScript; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Src : constant String := UI.Get_Attribute (Context => Context, Name => "src"); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if Src'Length > 0 then Writer.Queue_Include_Script (URL => Src, Async => UI.Get_Attribute (Context => Context, Name => "async")); end if; end; end Encode_Begin; end ASF.Components.Utils.Scripts;
Implement the Encode_Begin procedure to test if the <util:script> component defines a 'src' attribute and generate a <script> command to load the specified javascript source
Implement the Encode_Begin procedure to test if the <util:script> component defines a 'src' attribute and generate a <script> command to load the specified javascript source
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
78277f3bbd1d741e73a0d62e3695f2e10ae18701
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_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;
----------------------------------------------------------------------- -- 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"; function Sys_Realpath (S : in Ptr; R : in Ptr) return Ptr with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "realpath"; -- 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 the Sys_Realpath function (taken from Porion)
Declare the Sys_Realpath function (taken from Porion)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
882cd0a9745fe993f50a769aeb98f74637165e42
regtests/ado-tests.adb
regtests/ado-tests.adb
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Databases; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Util.Log; use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Fail (T : in Test; Message : in String); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Fail (T : in Test; Message : in String) is begin T.Assert (False, Message); end Fail; procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; Fail (T, "Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; Fail (T, "Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; use type ADO.Databases.Connection_Status; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Conn : constant ADO.Databases.Connection'Class := DB.Get_Connection; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin T.Assert (Conn.Get_Status = ADO.Databases.OPEN, "The database connection is open"); T.Assert (DB.Get_Status = ADO.Databases.OPEN, "The database connection is open"); Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use ADO.Objects; use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Unbounded_String; begin for I in 1 .. 127 loop Append (Name, Character'Val (I)); end loop; Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use ADO.Objects; use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); end Test_Blob; -- ------------------------------ -- Test the To_Object and To_Identifier operations. -- ------------------------------ procedure Test_Identifier_To_Object (T : in out Test) is Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER); begin T.Assert (Util.Beans.Objects.Is_Null (Val), "To_Object must return null for ADO.NO_IDENTIFIER"); T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER, "To_Identifier must return ADO.NO_IDENTIFIER for null"); Val := ADO.Utils.To_Object (1); T.Assert (not Util.Beans.Objects.Is_Null (Val), "To_Object must not return null for a valid Identifier"); T.Assert (ADO.Utils.To_Identifier (Val) = 1, "To_Identifier must return the correct identifier"); end Test_Identifier_To_Object; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier", Test_Identifier_To_Object'Access); end Add_Tests; end ADO.Tests;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Databases; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; 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.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; T.Fail ("Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; use type ADO.Databases.Connection_Status; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Conn : constant ADO.Databases.Connection'Class := DB.Get_Connection; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin T.Assert (Conn.Get_Status = ADO.Databases.OPEN, "The database connection is open"); T.Assert (DB.Get_Status = ADO.Databases.OPEN, "The database connection is open"); Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use ADO.Objects; use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Unbounded_String; begin for I in 1 .. 127 loop Append (Name, Character'Val (I)); end loop; Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use ADO.Objects; use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); 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;
Update the blog image test to verify more Create_Blob operations
Update the blog image test to verify more Create_Blob operations
Ada
apache-2.0
stcarrez/ada-ado
ec96cd61c06600e11affe10fec8866a1f6893a8a
src/sys/processes/util-processes.adb
src/sys/processes/util-processes.adb
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- Copyright (C) 2011, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- 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; -- ------------------------------ -- 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) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Proc.Sys := new Util.Processes.Os.System_Process; -- Build the argc/argv table, terminate by NULL for I in Arguments'Range loop Proc.Sys.Append_Argument (Arguments (I).all); end loop; -- Prepare to redirect the input/output/error streams. 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); 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 Pos : Natural := Command'First; N : Natural; begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); if Proc.Sys /= null then Proc.Sys.Finalize; Free (Proc.Sys); end if; Proc.Sys := new Util.Processes.Os.System_Process; 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 -- 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 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) 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) is begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); -- if Proc.Sys /= null then -- Proc.Sys.Finalize; -- Free (Proc.Sys); -- end if; -- Proc.Sys := new Util.Processes.Os.System_Process; Proc.Sys.Clear_Arguments; -- Build the argc/argv table, terminate by NULL for I in Arguments'Range loop Proc.Sys.Append_Argument (Arguments (I).all); end loop; -- Prepare to redirect the input/output/error streams. 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); 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 Pos : Natural := Command'First; N : Natural; begin if Is_Running (Proc) then raise Invalid_State with "A process is running"; end if; Log.Info ("Starting process {0}", Command); -- if Proc.Sys /= null then -- Proc.Sys.Finalize; -- Free (Proc.Sys); -- end if; -- Proc.Sys := new Util.Processes.Os.System_Process; 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 -- 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 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;
Implement Set_Environment procedures
Implement Set_Environment procedures
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
93ad7b4c595027fa6cddc717e9ee1e7cec951675
ARM/STMicro/STM32/drivers/stm32-syscfg.adb
ARM/STMicro/STM32/drivers/stm32-syscfg.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f407xx.h et al. -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief CMSIS STM32F407xx Device Peripheral Access Layer Header File. -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ -- This file provides register definitions for the STM32F4 (ARM Cortex M4F) -- microcontrollers from ST Microelectronics. with STM32_SVD.EXTI; use STM32_SVD.EXTI; with STM32_SVD.SYSCFG; use STM32_SVD.SYSCFG; with STM32.EXTI; with STM32.Device; use STM32.Device; package body STM32.SYSCFG is procedure Connect_External_Interrupt (Port : GPIO_Port; Pin : GPIO_Pin_Index) is CR_Index : Integer range 0 .. 3; EXTI_Index : Integer range EXTI_Field_Array'Range; Port_Name : constant GPIO_Port_Id := As_GPIO_Port_Id (Port); begin -- First we find the control register, of the four possible, that -- contains the EXTI_n value for pin 'n' specified by the Pin parameter. -- In effect, this is what we are doing for the EXTICR index: -- case GPIO_Pin'Pos (Pin) is -- when 0 .. 3 => CR_Index := 0; -- when 4 .. 7 => CR_Index := 1; -- when 8 .. 11 => CR_Index := 2; -- when 12 .. 15 => CR_Index := 3; -- end case; -- Note that that means we are dependent upon the order of the Pin -- declarations because we require GPIO_Pin'Pos(Pin_n) to be 'n', ie -- Pin_0 should be at position 0, Pin_1 at position 1, and so forth. CR_Index := Pin / 4; -- Now we must find which EXTI_n value to use, of the four possible, -- within the control register. We are depending on the GPIO_Port type -- being an enumeration and that the enumeral order is alphabetical on -- the Port letter, such that in effect GPIO_A'Pos = 0, GPIO_B'Pos = 1, -- and so on. EXTI_Index := GPIO_Port_Id'Pos (Port_Name) mod 4; -- ie 0 .. 3 -- Finally we assign the port 'number' to the EXTI_n value within the -- control register. We depend upon the Port enumerals' underlying -- numeric representation values matching what the hardware expects, -- that is, the values 0 .. n-1, which we get automatically unless -- overridden. case CR_Index is when 0 => SYSCFG_Periph.EXTICR1.EXTI.Arr (EXTI_Index) := GPIO_Port_Id'Enum_Rep (Port_Name); when 1 => SYSCFG_Periph.EXTICR2.EXTI.Arr (EXTI_Index) := GPIO_Port_Id'Enum_Rep (Port_Name); when 2 => SYSCFG_Periph.EXTICR3.EXTI.Arr (EXTI_Index) := GPIO_Port_Id'Enum_Rep (Port_Name); when 3 => SYSCFG_Periph.EXTICR4.EXTI.Arr (EXTI_Index) := GPIO_Port_Id'Enum_Rep (Port_Name); end case; end Connect_External_Interrupt; -------------------------------- -- Connect_External_Interrupt -- -------------------------------- procedure Connect_External_Interrupt (Port : GPIO_Port; Pin : GPIO_Pin) is begin Connect_External_Interrupt (Port, GPIO_Pin'Pos (Pin)); end Connect_External_Interrupt; -------------------------------- -- Connect_External_Interrupt -- -------------------------------- procedure Connect_External_Interrupt (Point : GPIO_Point) is begin Connect_External_Interrupt (Point.Port.all, Point.Pin); end Connect_External_Interrupt; -------------------------------- -- Connect_External_Interrupt -- -------------------------------- procedure Connect_External_Interrupt (Port : GPIO_Port; Pins : GPIO_Pins) is begin for Pin of Pins loop Connect_External_Interrupt (Port, Pin); end loop; end Connect_External_Interrupt; ------------------------------ -- Clear_External_Interrupt -- ------------------------------ procedure Clear_External_Interrupt (Pin : GPIO_Pin) is use STM32.EXTI; begin Clear_External_Interrupt (External_Line_Number'Val (GPIO_Pin'Pos (Pin))); end Clear_External_Interrupt; ------------------------------ -- Clear_External_Interrupt -- ------------------------------ procedure Clear_External_Interrupt (Pin : GPIO_Pin_Index) is begin EXTI_Periph.PR.PR.Arr (Pin) := 1; -- Set to 1 to clear end Clear_External_Interrupt; end STM32.SYSCFG;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f407xx.h et al. -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief CMSIS STM32F407xx Device Peripheral Access Layer Header File. -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ -- This file provides register definitions for the STM32F4 (ARM Cortex M4F) -- microcontrollers from ST Microelectronics. with STM32_SVD.EXTI; use STM32_SVD.EXTI; with STM32_SVD.SYSCFG; use STM32_SVD.SYSCFG; with STM32.EXTI; with STM32.Device; use STM32.Device; package body STM32.SYSCFG is procedure Connect_External_Interrupt (Port : GPIO_Port; Pin : GPIO_Pin_Index) is CR_Index : Integer range 0 .. 3; EXTI_Index : Integer range EXTI_Field_Array'Range; Port_Name : constant GPIO_Port_Id := As_GPIO_Port_Id (Port); begin -- First we find the control register, of the four possible, that -- contains the EXTI_n value for pin 'n' specified by the Pin parameter. -- In effect, this is what we are doing for the EXTICR index: -- case GPIO_Pin'Pos (Pin) is -- when 0 .. 3 => CR_Index := 0; -- when 4 .. 7 => CR_Index := 1; -- when 8 .. 11 => CR_Index := 2; -- when 12 .. 15 => CR_Index := 3; -- end case; -- Note that that means we are dependent upon the order of the Pin -- declarations because we require GPIO_Pin'Pos(Pin_n) to be 'n', ie -- Pin_0 should be at position 0, Pin_1 at position 1, and so forth. CR_Index := Pin / 4; -- Now we must find which EXTI_n value to use, of the four possible, -- within the control register. It is set to the actual line to activate -- among the 4 accessible by the EXTICR: -- EXTICR1: EXTI0 .. EXTI3 -- EXTICR2: EXTI4 .. EXTI7 -- EXTICR3: EXTI8 .. EXTI11 -- EXTICR4: EXTI12 .. EXTI15 EXTI_Index := Pin mod 4; -- ie 0 .. 3 -- Finally we assign the port 'number' to the EXTI_n value within the -- control register. We depend upon the Port enumerals' underlying -- numeric representation values matching what the hardware expects, -- that is, the values 0 .. n-1, which we get automatically unless -- overridden. case CR_Index is when 0 => SYSCFG_Periph.EXTICR1.EXTI.Arr (EXTI_Index) := GPIO_Port_Id'Enum_Rep (Port_Name); when 1 => SYSCFG_Periph.EXTICR2.EXTI.Arr (EXTI_Index) := GPIO_Port_Id'Enum_Rep (Port_Name); when 2 => SYSCFG_Periph.EXTICR3.EXTI.Arr (EXTI_Index) := GPIO_Port_Id'Enum_Rep (Port_Name); when 3 => SYSCFG_Periph.EXTICR4.EXTI.Arr (EXTI_Index) := GPIO_Port_Id'Enum_Rep (Port_Name); end case; end Connect_External_Interrupt; -------------------------------- -- Connect_External_Interrupt -- -------------------------------- procedure Connect_External_Interrupt (Port : GPIO_Port; Pin : GPIO_Pin) is begin Connect_External_Interrupt (Port, GPIO_Pin'Pos (Pin)); end Connect_External_Interrupt; -------------------------------- -- Connect_External_Interrupt -- -------------------------------- procedure Connect_External_Interrupt (Point : GPIO_Point) is begin Connect_External_Interrupt (Point.Port.all, Point.Pin); end Connect_External_Interrupt; -------------------------------- -- Connect_External_Interrupt -- -------------------------------- procedure Connect_External_Interrupt (Port : GPIO_Port; Pins : GPIO_Pins) is begin for Pin of Pins loop Connect_External_Interrupt (Port, Pin); end loop; end Connect_External_Interrupt; ------------------------------ -- Clear_External_Interrupt -- ------------------------------ procedure Clear_External_Interrupt (Pin : GPIO_Pin) is use STM32.EXTI; begin Clear_External_Interrupt (External_Line_Number'Val (GPIO_Pin'Pos (Pin))); end Clear_External_Interrupt; ------------------------------ -- Clear_External_Interrupt -- ------------------------------ procedure Clear_External_Interrupt (Pin : GPIO_Pin_Index) is begin EXTI_Periph.PR.PR.Arr (Pin) := 1; -- Set to 1 to clear end Clear_External_Interrupt; end STM32.SYSCFG;
Fix invalid EXTI activation in SYSCFG.
Fix invalid EXTI activation in SYSCFG.
Ada
bsd-3-clause
lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library
d081a00c37496d20f1f9040d3acaa6bc161dfde0
src/cbap.ads
src/cbap.ads
------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: ISC License (see COPYING file) -- -- -- -- Copyright © 2015 darkestkhan -- ------------------------------------------------------------------------------ -- Permission to use, copy, modify, and/or distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- The software is provided "as is" and the author disclaims all warranties -- -- with regard to this software including all implied warranties of -- -- merchantability and fitness. In no event shall the author be liable for -- -- any special, direct, indirect, or consequential damages or any damages -- -- whatsoever resulting from loss of use, data or profits, whether in an -- -- action of contract, negligence or other tortious action, arising out of -- -- or in connection with the use or performance of this software. -- ------------------------------------------------------------------------------ with Ada.Containers.Indefinite_Vectors; ------------------------------------------------------------------------------ -- Small and simple callback based library for processing program arguments -- ------------------------------------------------------------------------------ --------------------------------------------------------------------------- -- U S A G E -- --------------------------------------------------------------------------- -- First register all callbacks you are interested in, then call -- Process_Arguments. -- -- NOTE: "=" sign can't be part of argument name for registered callback. -- -- Only one callback can be registered per argument, otherwise -- Constraint_Error is propagated. --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- Leading single hyphen and double hyphen are stripped (if present) when -- processing arguments that are placed before first "--" argument, -- so ie. "--help", "-help" and "help" are functionally -- equivalent, treated as if "help" was actually passed in all 3 cases. -- (you should register callback just for "help", if you register it for -- "--help" then actually passed argument would have to be "----help" in order -- for it to trigger said callback) -- -- In addition if you registered callback as case insensitive, then -- (using above example) "Help", "HELP", "help" and "HeLp" all would result in -- call to said callback. -- -- If Argument_Type is Variable then callback will receive part of argument -- that is after "=" sign. (ie. "OS=Linux" argument would result in callback -- receiving only "Linux" as its argument), otherwise actual argument will be -- passed. -- -- For Variable, case insensitive callbacks simple rule applies: -- only variable name is case insensitive, with actual value (when passed to -- program) being unchanged. -- -- If argument for which callback is registered is passed few times -- (ie. ./program help help help) then callback is triggered however many -- times said argument is detected. -- -- All arguments with no associated callback are added to Unknown_Arguments -- vector as long as they appear before first "--" argument. -- -- All arguments after first "--" (standalone double hyphen) are added to -- Input_Argument vector (this includes another "--"), w/o any kind of -- hyphen stripping being performed on them. -- -- NOTE: No care is taken to ensure that all Input_Arguments -- (or Unknown_Arguments) are unique. --------------------------------------------------------------------------- package CBAP is --------------------------------------------------------------------------- -- Yes, I do realize this is actually vector... package Argument_Lists is new Ada.Containers.Indefinite_Vectors (Positive, String); -- List of all arguments (before first "--" argument) for which callbacks -- where not registered. Unknown_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector; -- List of all arguments after first "--" argument. Input_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector; -- Argument_Types decides if argument is just a simple value, or a variable -- with value assigned to it (difference between "--val" and "--var=val") type Argument_Types is (Value, Variable); -- Argument is useful mostly for Variable type of arguments. type Callbacks is not null access procedure (Argument: in String); --------------------------------------------------------------------------- -- Register callbacks for processing arguments. -- @Callback : Action to be performed in case appropriate argument is -- detected. -- @Called_On : Argument for which callback is to be performed. -- @Argument_Type : {Value, Variable}. Value is simple argument that needs no -- additional parsing. Variable is argument of "Arg_Name=Some_Val" form. -- When callback is triggered, Value is passed to callback as input, in -- case of Variable it is content of argument after first "=" that is -- passed to callback. -- @Case_Sensitive: Whether or not case is significant. When False all forms -- of argument are treated as if written in lower case. procedure Register ( Callback : in Callbacks; Called_On : in String; Argument_Type : in Argument_Types := Value; Case_Sensitive: in Boolean := True ); -- Raised if Called_On contains "=". Incorrect_Called_On: exception; --------------------------------------------------------------------------- -- Parse arguments supplied to program, calling callbacks when argument with -- associated callback is detected. -- NOTE: Process_Arguments will call callbacks however many times argument -- with associated callback is called. So if you have callback for "help", -- then ./program help help help -- will result in 3 calls to said callback. procedure Process_Arguments; --------------------------------------------------------------------------- end CBAP;
------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: ISC License (see COPYING file) -- -- -- -- Copyright © 2015 darkestkhan -- ------------------------------------------------------------------------------ -- Permission to use, copy, modify, and/or distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- The software is provided "as is" and the author disclaims all warranties -- -- with regard to this software including all implied warranties of -- -- merchantability and fitness. In no event shall the author be liable for -- -- any special, direct, indirect, or consequential damages or any damages -- -- whatsoever resulting from loss of use, data or profits, whether in an -- -- action of contract, negligence or other tortious action, arising out of -- -- or in connection with the use or performance of this software. -- ------------------------------------------------------------------------------ with Ada.Containers.Indefinite_Vectors; ------------------------------------------------------------------------------ -- Small and simple callback based library for processing program arguments -- ------------------------------------------------------------------------------ --------------------------------------------------------------------------- -- U S A G E -- --------------------------------------------------------------------------- -- First register all callbacks you are interested in, then call -- Process_Arguments. -- -- NOTE: "=" sign can't be part of argument name for registered callback. -- -- Only one callback can be registered per argument, otherwise -- Constraint_Error is propagated. --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- Leading single hyphen and double hyphen are stripped (if present) when -- processing arguments that are placed before first "--" argument, -- so e.g. "--help", "-help" and "help" are functionally -- equivalent, treated as if "help" was actually passed in all 3 cases. -- (you should register callback just for "help", if you register it for -- "--help" then actually passed argument would have to be "----help" in order -- for it to trigger said callback) -- -- In addition if you registered callback as case insensitive, then -- (using above example) "Help", "HELP", "help" and "HeLp" all would result in -- call to said callback. -- -- If Argument_Type is Variable then callback will receive part of argument -- that is after "=" sign. (ie. "OS=Linux" argument would result in callback -- receiving only "Linux" as its argument), otherwise actual argument will be -- passed. -- -- For Variable, case insensitive callbacks simple rule applies: -- only variable name is case insensitive, with actual value (when passed to -- program) being unchanged. -- -- If argument for which callback is registered is passed few times -- (ie. ./program help help help) then callback is triggered however many -- times said argument is detected. -- -- NOTE that Check for case insensitive callback is being performed first, -- thus if you happen to register callback for "help" (case insensitive) and -- "HeLp" (case sensitive) then only the case insensitive one will be called -- (i.e. "help"). -- -- All arguments with no associated callback are added to Unknown_Arguments -- vector as long as they appear before first "--" argument. -- -- All arguments after first "--" (standalone double hyphen) are added to -- Input_Argument vector (this includes another "--"), w/o any kind of -- hyphen stripping being performed on them. -- -- NOTE: No care is taken to ensure that all Input_Arguments -- (or Unknown_Arguments) are unique. --------------------------------------------------------------------------- package CBAP is --------------------------------------------------------------------------- -- Yes, I do realize this is actually vector... package Argument_Lists is new Ada.Containers.Indefinite_Vectors (Positive, String); -- List of all arguments (before first "--" argument) for which callbacks -- where not registered. Unknown_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector; -- List of all arguments after first "--" argument. Input_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector; -- Argument_Types decides if argument is just a simple value, or a variable -- with value assigned to it (difference between "--val" and "--var=val") type Argument_Types is (Value, Variable); -- Argument is useful mostly for Variable type of arguments. type Callbacks is not null access procedure (Argument: in String); --------------------------------------------------------------------------- -- Register callbacks for processing arguments. -- @Callback : Action to be performed in case appropriate argument is -- detected. -- @Called_On : Argument for which callback is to be performed. -- @Argument_Type : {Value, Variable}. Value is simple argument that needs no -- additional parsing. Variable is argument of "Arg_Name=Some_Val" form. -- When callback is triggered, Value is passed to callback as input, in -- case of Variable it is content of argument after first "=" that is -- passed to callback. -- @Case_Sensitive: Whether or not case is significant. When False all forms -- of argument are treated as if written in lower case. procedure Register ( Callback : in Callbacks; Called_On : in String; Argument_Type : in Argument_Types := Value; Case_Sensitive: in Boolean := True ); -- Raised if Called_On contains "=". Incorrect_Called_On: exception; --------------------------------------------------------------------------- -- Parse arguments supplied to program, calling callbacks when argument with -- associated callback is detected. -- NOTE: Process_Arguments will call callbacks however many times argument -- with associated callback is called. So if you have callback for "help", -- then ./program help help help -- will result in 3 calls to said callback. procedure Process_Arguments; --------------------------------------------------------------------------- end CBAP;
Expand comment about edge case.
Expand comment about edge case. Signed-off-by: darkestkhan <[email protected]>
Ada
isc
darkestkhan/cbap
62476ffc9228c8b182882ecfcc06cbc68470076d
awa/src/awa-events.ads
awa/src/awa-events.ads
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with ASF.Applications; -- == Introduction == -- The <b>AWA.Events</b> package defines an event framework for modules to post events -- and have Ada bean methods be invoked when these events are dispatched. Subscription to -- events is done through configuration files. This allows to configure the modules and -- integrate them together easily at configuration time. -- -- 1/ Modules define the events that they can generate by instantiating the <b>Definition</b> -- package. This is a static definition of the event. Each event is given a unique name. -- -- package Event_New_User is new AWA.Events.Definition ("new-user"); -- -- 2/ The module can post an event to inform other modules or the system that a particular -- action occurred. The module creates the event instance of type <b>Module_Event</b> and -- populates that event with useful properties for event receivers. -- -- Event : AWA.Events.Module_Event; -- -- Event.Set_Event_Kind (Event_New_User.Kind); -- Event.Set_Parameter ("email", "[email protected]"); -- -- 3/ The module will post the event by using the <b>Send_Event</b> operation. -- -- Manager.Send_Event (Event); -- -- 4/ Modules or applications interested by a particular event will configure the event manager -- to dispatch the event to an Ada bean event action. The Ada bean is an object that must -- implement a procedure that matches the prototype: -- -- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...; -- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); -- -- The Ada bean method and object are registered as other Ada beans. -- -- 5/ The configuration file indicates how to bind the Ada bean action and the event together. -- The action is specified using an EL Method Expression (See Ada EL or JSR 245). -- -- <on-event name="new_user"> -- <action>#{ada_bean.action}</action> -- </on-event> -- -- == Data Model == -- @include Queues.hbm.xml -- package AWA.Events is type Queue_Index is new Natural; type Event_Index is new Natural; -- ------------------------------ -- Event kind definition -- ------------------------------ -- This package must be instantiated for each event that a module can post. generic Name : String; package Definition is function Kind return Event_Index; pragma Inline_Always (Kind); end Definition; -- Exception raised if an event name is not found. Not_Found : exception; -- Identifies an invalid event. Invalid_Event : constant Event_Index := 0; -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. function Find_Event_Index (Name : in String) return Event_Index; -- ------------------------------ -- Module event -- ------------------------------ type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private; type Module_Event_Access is access all Module_Event'Class; -- Set the event type which identifies the event. procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index); -- Get the event type which identifies the event. function Get_Event_Kind (Event : in Module_Event) return Event_Index; -- Set a parameter on the message. procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String); -- Get the parameter with the given name. function Get_Parameter (Event : in Module_Event; Name : in String) return String; -- Get the value that corresponds to the parameter with the given name. overriding function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object; private type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record Kind : Event_Index := Invalid_Event; Props : ASF.Applications.Config; end record; -- The index of the last event definition. Last_Event : Event_Index := 0; -- Get the event type name. function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access; -- Make and return a copy of the event. function Copy (Event : in Module_Event) return Module_Event_Access; end AWA.Events;
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with ASF.Applications; -- == Introduction == -- The <b>AWA.Events</b> package defines an event framework for modules to post events -- and have Ada bean methods be invoked when these events are dispatched. Subscription to -- events is done through configuration files. This allows to configure the modules and -- integrate them together easily at configuration time. -- -- Modules define the events that they can generate by instantiating the <b>Definition</b> -- package. This is a static definition of the event. Each event is given a unique name. -- -- package Event_New_User is new AWA.Events.Definition ("new-user"); -- -- The module can post an event to inform other modules or the system that a particular -- action occurred. The module creates the event instance of type <b>Module_Event</b> and -- populates that event with useful properties for event receivers. -- -- Event : AWA.Events.Module_Event; -- -- Event.Set_Event_Kind (Event_New_User.Kind); -- Event.Set_Parameter ("email", "[email protected]"); -- -- The module will post the event by using the <b>Send_Event</b> operation. -- -- Manager.Send_Event (Event); -- -- Modules or applications interested by a particular event will configure the event manager -- to dispatch the event to an Ada bean event action. The Ada bean is an object that must -- implement a procedure that matches the prototype: -- -- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...; -- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); -- -- The Ada bean method and object are registered as other Ada beans. -- -- The configuration file indicates how to bind the Ada bean action and the event together. -- The action is specified using an EL Method Expression (See Ada EL or JSR 245). -- -- <on-event name="new_user"> -- <action>#{ada_bean.action}</action> -- </on-event> -- -- == Data Model == -- @include Queues.hbm.xml -- package AWA.Events is type Queue_Index is new Natural; type Event_Index is new Natural; -- ------------------------------ -- Event kind definition -- ------------------------------ -- This package must be instantiated for each event that a module can post. generic Name : String; package Definition is function Kind return Event_Index; pragma Inline_Always (Kind); end Definition; -- Exception raised if an event name is not found. Not_Found : exception; -- Identifies an invalid event. Invalid_Event : constant Event_Index := 0; -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. function Find_Event_Index (Name : in String) return Event_Index; -- ------------------------------ -- Module event -- ------------------------------ type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private; type Module_Event_Access is access all Module_Event'Class; -- Set the event type which identifies the event. procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index); -- Get the event type which identifies the event. function Get_Event_Kind (Event : in Module_Event) return Event_Index; -- Set a parameter on the message. procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String); -- Get the parameter with the given name. function Get_Parameter (Event : in Module_Event; Name : in String) return String; -- Get the value that corresponds to the parameter with the given name. overriding function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object; private type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record Kind : Event_Index := Invalid_Event; Props : ASF.Applications.Config; end record; -- The index of the last event definition. Last_Event : Event_Index := 0; -- Get the event type name. function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access; -- Make and return a copy of the event. function Copy (Event : in Module_Event) return Module_Event_Access; end AWA.Events;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
3f4367954bcb260176d08a516d0fcb66ac4c2884
awa/plugins/awa-jobs/src/awa-jobs-beans.ads
awa/plugins/awa-jobs/src/awa-jobs-beans.ads
----------------------------------------------------------------------- -- awa-jobs-beans -- AWA Jobs 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 Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; with AWA.Events; with AWA.Jobs.Services; with AWA.Jobs.Modules; package AWA.Jobs.Beans is -- The <tt>Process_Bean</tt> is the Ada bean that receives the job event and -- performs the job action associated with it. type Process_Bean is limited new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with private; type Process_Bean_Access is access all Process_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Process_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Process_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Process_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Execute the job described by the event. procedure Execute (Bean : in out Process_Bean; Event : in AWA.Events.Module_Event'Class); -- Create the job process bean instance. function Create_Process_Bean (Module : in AWA.Jobs.Modules.Job_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; private type Process_Bean is limited new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Jobs.Modules.Job_Module_Access; Job : AWA.Jobs.Services.Job_Ref; end record; end AWA.Jobs.Beans;
----------------------------------------------------------------------- -- awa-jobs-beans -- AWA Jobs Ada Beans -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; with AWA.Events; with AWA.Jobs.Services; with AWA.Jobs.Modules; package AWA.Jobs.Beans is -- The <tt>Process_Bean</tt> is the Ada bean that receives the job event and -- performs the job action associated with it. type Process_Bean is limited new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with private; type Process_Bean_Access is access all Process_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Process_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Process_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Process_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Execute the job described by the event. procedure Execute (Bean : in out Process_Bean; Event : in AWA.Events.Module_Event'Class); -- Create the job process bean instance. function Create_Process_Bean (Module : in AWA.Jobs.Modules.Job_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; private type Process_Bean is limited new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Jobs.Modules.Job_Module_Access; Job : AWA.Jobs.Services.Job_Ref; end record; end AWA.Jobs.Beans;
Update copyright year
Update copyright year
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
891b9e8c9b922d104c77fe6b3498be91c34600c4
boards/stm32f469_discovery/stm32-board.ads
boards/stm32f469_discovery/stm32-board.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This file provides declarations for devices on the STM32F469 Discovery kits -- manufactured by ST Microelectronics. with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; with STM32.FMC; use STM32.FMC; with Ada.Interrupts.Names; use Ada.Interrupts; use STM32; -- for base addresses -- with STM32.I2C; use STM32.I2C; with Framebuffer_OTM8009A; with Touch_Panel_FT6x06; package STM32.Board is pragma Elaborate_Body; subtype User_LED is GPIO_Point; Green : User_LED renames LED1; Orange : User_LED renames LED2; Red : User_LED renames LED3; Blue : User_LED renames LED4; LCH_LED : User_LED renames Red; All_LEDs : GPIO_Points := Green & Orange & Red & Blue; procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Turn_On (This : in out User_LED) renames STM32.GPIO.Clear; procedure Turn_Off (This : in out User_LED) renames STM32.GPIO.Set; procedure All_LEDs_Off with Inline; procedure All_LEDs_On with Inline; procedure Toggle_LEDs (These : in out GPIO_Points) renames STM32.GPIO.Toggle; -- Gyro : Three_Axis_Gyroscope; -- GPIO Pins for FMC FMC_D : constant GPIO_Points := (PD0, PD1, PD8, PD9, PD10, PD14, PD15, PE7, PE8, PE9, PE10, PE11, PE12, PE13, PE14, PE15, PH8, PH9, PH10, PH11, PH12, PH13, PH14, PH15, PI0, PI1, PI2, PI3, PI6, PI7, PI9, PI10); FMC_A : constant GPIO_Points := (PF0, PF1, PF2, PF3, PF4, PF5, PF12, PF13, PF14, PF15, PG0, PG1, PG4, PG5); FMC_SDNWE : GPIO_Point renames PC0; FMC_SDNRAS : GPIO_Point renames PF11; FMC_SDNCAS : GPIO_Point renames PG15; FMC_SDNE0 : GPIO_Point renames PH3; FMC_SDCKE0 : GPIO_Point renames PH2; FMC_SDCLK : GPIO_Point renames PG8; FMC_NBL0 : GPIO_Point renames PE0; FMC_NBL1 : GPIO_Point renames PE1; FMC_NBL2 : GPIO_Point renames PI4; FMC_NBL3 : GPIO_Point renames PI5; SDRAM_PINS : constant GPIO_Points := FMC_A & FMC_D & FMC_SDNWE & FMC_SDNRAS & FMC_SDNCAS & FMC_SDCLK & FMC_SDNE0 & FMC_SDCKE0 & FMC_NBL0 & FMC_NBL1 & FMC_NBL2 & FMC_NBL3; -- SDRAM CONFIGURATION Parameters SDRAM_Base : constant := 16#C0000000#; SDRAM_Size : constant := 16#800000#; SDRAM_Bank : constant STM32.FMC.FMC_SDRAM_Cmd_Target_Bank := STM32.FMC.FMC_Bank1_SDRAM; SDRAM_Mem_Width : constant STM32.FMC.FMC_SDRAM_Memory_Bus_Width := STM32.FMC.FMC_SDMemory_Width_32b; SDRAM_Row_Bits : constant STM32.FMC.FMC_SDRAM_Row_Address_Bits := FMC_RowBits_Number_11b; SDRAM_CAS_Latency : constant STM32.FMC.FMC_SDRAM_CAS_Latency := STM32.FMC.FMC_CAS_Latency_3; SDRAM_CLOCK_Period : constant STM32.FMC.FMC_SDRAM_Clock_Configuration := STM32.FMC.FMC_SDClock_Period_2; SDRAM_Read_Burst : constant STM32.FMC.FMC_SDRAM_Burst_Read := STM32.FMC.FMC_Read_Burst_Single; SDRAM_Read_Pipe : constant STM32.FMC.FMC_SDRAM_Read_Pipe_Delay := STM32.FMC.FMC_ReadPipe_Delay_0; SDRAM_Refresh_Cnt : constant := 16#0569#; --------------- -- SPI5 Pins -- --------------- -- SPI5_SCK : GPIO_Point renames PF7; -- SPI5_MISO : GPIO_Point renames PF8; -- SPI5_MOSI : GPIO_Point renames PF9; -- NCS_MEMS_SPI : GPIO_Point renames PC1; -- MEMS_INT1 : GPIO_Point renames PA1; -- MEMS_INT2 : GPIO_Point renames PA2; -- LCD_SPI : SPI_Port renames SPI_5; -------------------------------- -- Screen/Touch panel devices -- -------------------------------- LCD_Natural_Width : constant := Framebuffer_OTM8009A.LCD_Natural_Width; LCD_Natural_Height : constant := Framebuffer_OTM8009A.LCD_Natural_Height; Display : Framebuffer_OTM8009A.Frame_Buffer; Touch_Panel : Touch_Panel_FT6x06.Touch_Panel; ----------------- -- Touch Panel -- ----------------- I2C1_SCL : GPIO_Point renames PB8; I2C1_SDA : GPIO_Point renames PB9; TP_INT : GPIO_Point renames PJ5; TP_Pins : constant GPIO_Points := (I2C1_SCL, I2C1_SDA); -- User button User_Button_Point : GPIO_Point renames PA0; User_Button_Interrupt : constant Interrupt_ID := Names.EXTI0_Interrupt; procedure Configure_User_Button_GPIO; -- Configures the GPIO port/pin for the blue user button. Sufficient -- for polling the button, and necessary for having the button generate -- interrupts. end STM32.Board;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This file provides declarations for devices on the STM32F469 Discovery kits -- manufactured by ST Microelectronics. with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; with STM32.FMC; use STM32.FMC; with Ada.Interrupts.Names; use Ada.Interrupts; use STM32; -- for base addresses -- with STM32.I2C; use STM32.I2C; with Framebuffer_OTM8009A; with Touch_Panel_FT6x06; package STM32.Board is pragma Elaborate_Body; subtype User_LED is GPIO_Point; Green : User_LED renames PG6; Orange : User_LED renames PD4; Red : User_LED renames PD5; Blue : User_LED renames PK3; LCH_LED : User_LED renames Red; All_LEDs : GPIO_Points := Green & Orange & Red & Blue; procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Turn_On (This : in out User_LED) renames STM32.GPIO.Clear; procedure Turn_Off (This : in out User_LED) renames STM32.GPIO.Set; procedure All_LEDs_Off with Inline; procedure All_LEDs_On with Inline; procedure Toggle_LEDs (These : in out GPIO_Points) renames STM32.GPIO.Toggle; -- Gyro : Three_Axis_Gyroscope; -- GPIO Pins for FMC FMC_D : constant GPIO_Points := (PD0, PD1, PD8, PD9, PD10, PD14, PD15, PE7, PE8, PE9, PE10, PE11, PE12, PE13, PE14, PE15, PH8, PH9, PH10, PH11, PH12, PH13, PH14, PH15, PI0, PI1, PI2, PI3, PI6, PI7, PI9, PI10); FMC_A : constant GPIO_Points := (PF0, PF1, PF2, PF3, PF4, PF5, PF12, PF13, PF14, PF15, PG0, PG1, PG4, PG5); FMC_SDNWE : GPIO_Point renames PC0; FMC_SDNRAS : GPIO_Point renames PF11; FMC_SDNCAS : GPIO_Point renames PG15; FMC_SDNE0 : GPIO_Point renames PH3; FMC_SDCKE0 : GPIO_Point renames PH2; FMC_SDCLK : GPIO_Point renames PG8; FMC_NBL0 : GPIO_Point renames PE0; FMC_NBL1 : GPIO_Point renames PE1; FMC_NBL2 : GPIO_Point renames PI4; FMC_NBL3 : GPIO_Point renames PI5; SDRAM_PINS : constant GPIO_Points := FMC_A & FMC_D & FMC_SDNWE & FMC_SDNRAS & FMC_SDNCAS & FMC_SDCLK & FMC_SDNE0 & FMC_SDCKE0 & FMC_NBL0 & FMC_NBL1 & FMC_NBL2 & FMC_NBL3; -- SDRAM CONFIGURATION Parameters SDRAM_Base : constant := 16#C0000000#; SDRAM_Size : constant := 16#800000#; SDRAM_Bank : constant STM32.FMC.FMC_SDRAM_Cmd_Target_Bank := STM32.FMC.FMC_Bank1_SDRAM; SDRAM_Mem_Width : constant STM32.FMC.FMC_SDRAM_Memory_Bus_Width := STM32.FMC.FMC_SDMemory_Width_32b; SDRAM_Row_Bits : constant STM32.FMC.FMC_SDRAM_Row_Address_Bits := FMC_RowBits_Number_11b; SDRAM_CAS_Latency : constant STM32.FMC.FMC_SDRAM_CAS_Latency := STM32.FMC.FMC_CAS_Latency_3; SDRAM_CLOCK_Period : constant STM32.FMC.FMC_SDRAM_Clock_Configuration := STM32.FMC.FMC_SDClock_Period_2; SDRAM_Read_Burst : constant STM32.FMC.FMC_SDRAM_Burst_Read := STM32.FMC.FMC_Read_Burst_Single; SDRAM_Read_Pipe : constant STM32.FMC.FMC_SDRAM_Read_Pipe_Delay := STM32.FMC.FMC_ReadPipe_Delay_0; SDRAM_Refresh_Cnt : constant := 16#0569#; --------------- -- SPI5 Pins -- --------------- -- SPI5_SCK : GPIO_Point renames PF7; -- SPI5_MISO : GPIO_Point renames PF8; -- SPI5_MOSI : GPIO_Point renames PF9; -- NCS_MEMS_SPI : GPIO_Point renames PC1; -- MEMS_INT1 : GPIO_Point renames PA1; -- MEMS_INT2 : GPIO_Point renames PA2; -- LCD_SPI : SPI_Port renames SPI_5; -------------------------------- -- Screen/Touch panel devices -- -------------------------------- LCD_Natural_Width : constant := Framebuffer_OTM8009A.LCD_Natural_Width; LCD_Natural_Height : constant := Framebuffer_OTM8009A.LCD_Natural_Height; Display : Framebuffer_OTM8009A.Frame_Buffer; Touch_Panel : Touch_Panel_FT6x06.Touch_Panel; ----------------- -- Touch Panel -- ----------------- I2C1_SCL : GPIO_Point renames PB8; I2C1_SDA : GPIO_Point renames PB9; TP_INT : GPIO_Point renames PJ5; TP_Pins : constant GPIO_Points := (I2C1_SCL, I2C1_SDA); -- User button User_Button_Point : GPIO_Point renames PA0; User_Button_Interrupt : constant Interrupt_ID := Names.EXTI0_Interrupt; procedure Configure_User_Button_GPIO; -- Configures the GPIO port/pin for the blue user button. Sufficient -- for polling the button, and necessary for having the button generate -- interrupts. end STM32.Board;
Fix the LED decls
Fix the LED decls
Ada
bsd-3-clause
ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
6dabb0d1b16d261405e79918f1e928a546597ff7
src/http/util-http-rest.ads
src/http/util-http-rest.ads
----------------------------------------------------------------------- -- util-http-rest -- REST API support -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.IO; with Util.Http.Clients; with Util.Serialize.Mappers.Record_Mapper; -- The <b>Util.Http.Rest</b> package defines a REST client type which helps in writing -- REST client APIs. A REST client is similar to an HTTP client but it provides additional -- operations that are useful in REST APIs. package Util.Http.Rest is -- ----------------------- -- REST client -- ----------------------- type Client is new Util.Http.Clients.Client with private; -- Execute an HTTP GET operation using the <b>Http</b> client on the given <b>URI</b>. -- Upon successful reception of the response, parse the JSON result and populate the -- serialization context associated with the parser. procedure Get (Http : in out Client; URI : in String; Parser : in out Util.Serialize.IO.Parser'Class); -- Execute an HTTP GET operation on the given <b>URI</b> and parse the JSON response -- into the target object refered to by <b>Into</b> by using the mapping described -- in <b>Mapping</b>. generic -- Package that maps the element into a record. with package Element_Mapper is new Util.Serialize.Mappers.Record_Mapper (<>); procedure Rest_Get (URI : in String; Mapping : in Util.Serialize.Mappers.Mapper_Access; Path : in String := ""; Into : in Element_Mapper.Element_Type_Access); private type Client is new Util.Http.Clients.Client with record Status : Natural := 0; end record; end Util.Http.Rest;
----------------------------------------------------------------------- -- util-http-rest -- REST API support -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.IO; with Util.Http.Clients; with Util.Serialize.Mappers.Record_Mapper; -- The <b>Util.Http.Rest</b> package defines a REST client type which helps in writing -- REST client APIs. A REST client is similar to an HTTP client but it provides additional -- operations that are useful in REST APIs. package Util.Http.Rest is -- ----------------------- -- REST client -- ----------------------- type Client is new Util.Http.Clients.Client with private; -- Execute an HTTP GET operation using the <b>Http</b> client on the given <b>URI</b>. -- Upon successful reception of the response, parse the JSON result and populate the -- serialization context associated with the parser. procedure Get (Http : in out Client; URI : in String; Parser : in out Util.Serialize.IO.Parser'Class; Sink : in out Util.Serialize.IO.Reader'Class); -- Execute an HTTP GET operation on the given <b>URI</b> and parse the JSON response -- into the target object refered to by <b>Into</b> by using the mapping described -- in <b>Mapping</b>. generic -- Package that maps the element into a record. with package Element_Mapper is new Util.Serialize.Mappers.Record_Mapper (<>); procedure Rest_Get (URI : in String; Mapping : in Util.Serialize.Mappers.Mapper_Access; Path : in String := ""; Into : in Element_Mapper.Element_Type_Access); private type Client is new Util.Http.Clients.Client with record Status : Natural := 0; end record; end Util.Http.Rest;
Add a Reader class parameter to the Get procedure
Add a Reader class parameter to the Get procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f77bba82476fa06a18f85be8240605326f5917ad
orka/src/gl/windows/gl-loader.adb
orka/src/gl/windows/gl-loader.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2018 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package body GL.Loader is pragma Linker_Options ("-lkernel32", "-lopengl32"); function Get_Proc_Address (Name : Interfaces.C.char_array) return System.Address is use type System.Address; function WGL_Get_Proc_Address (Name : Interfaces.C.char_array) return System.Address with Import, Convention => StdCall, External_Name => "wglGetProcAddress"; function Old_Get_Proc_Address (Handle : System.Address; Name : Interfaces.C.char_array) return System.Address with Import, Convention => StdCall, External_Name => "GetProcAddress"; function Get_Module_Handle (Name : Interfaces.C.char_array) return System.Address with Import, Convention => StdCall, External_Name => "GetModuleHandleA"; Result : constant System.Address := WGL_Get_Proc_Address (Name); begin if Result /= System.Null_Address then return Result; else -- OpenGL 1.1 functions are directly exported in the opengl32 library return Old_Get_Proc_Address (Get_Module_Handle ("opengl32"), Name); end if; end Get_Proc_Address; end GL.Loader;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2018 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package body GL.Loader is pragma Linker_Options ("-lkernel32 -lopengl32"); function Get_Proc_Address (Name : Interfaces.C.char_array) return System.Address is use type System.Address; function WGL_Get_Proc_Address (Name : Interfaces.C.char_array) return System.Address with Import, Convention => StdCall, External_Name => "wglGetProcAddress"; function Old_Get_Proc_Address (Handle : System.Address; Name : Interfaces.C.char_array) return System.Address with Import, Convention => StdCall, External_Name => "GetProcAddress"; function Get_Module_Handle (Name : Interfaces.C.char_array) return System.Address with Import, Convention => StdCall, External_Name => "GetModuleHandleA"; Result : constant System.Address := WGL_Get_Proc_Address (Name); begin if Result /= System.Null_Address then return Result; else -- OpenGL 1.1 functions are directly exported in the opengl32 library return Old_Get_Proc_Address (Get_Module_Handle ("opengl32"), Name); end if; end Get_Proc_Address; end GL.Loader;
Fix pragma Linker_Options in package GL.Loader on Windows
Fix pragma Linker_Options in package GL.Loader on Windows Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
a8d01de7a7e9a97ac7d3772577b2387fec14c4f9
src/wiki-attributes.ads
src/wiki-attributes.ads
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- === Attributes === -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List</tt> -- with some operations to append or query for an attribute. package Wiki.Attributes is pragma Preelaborate; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Wiki.Strings.UString; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List is private; -- Find the attribute with the given name. function Find (List : in Attribute_List; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.UString; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.UString; Value : in Wiki.Strings.UString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List); -- Iterate over the list attributes and call the <tt>Process</tt> procedure. procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)); private type Attribute (Name_Length, Value_Length : Natural) is limited new Util.Refs.Ref_Entity with record Name : String (1 .. Name_Length); Value : Wiki.Strings.WString (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Refs is new Util.Refs.Indefinite_References (Attribute, Attribute_Access); use Attribute_Refs; subtype Attribute_Ref is Attribute_Refs.Ref; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Ref); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List); end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- === Attributes === -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List</tt> -- with some operations to append or query for an attribute. package Wiki.Attributes is pragma Preelaborate; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Wiki.Strings.UString; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List is private; -- Find the attribute with the given name. function Find (List : in Attribute_List; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.UString; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.UString; Value : in Wiki.Strings.UString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List); -- Iterate over the list attributes and call the <tt>Process</tt> procedure. procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)); private type Attribute (Name_Length, Value_Length : Natural) is limited new Util.Refs.Ref_Entity with record Name : String (1 .. Name_Length); Value : Wiki.Strings.WString (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Refs is new Util.Refs.Indefinite_References (Attribute, Attribute_Access); use Attribute_Refs; subtype Attribute_Ref is Attribute_Refs.Ref; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Ref); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List); end Wiki.Attributes;
Declare a new Append procedure
Declare a new Append procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
a48f3a66a8d94955367a60cb1d0e9ef4646111f7
regtests/ado-testsuite.adb
regtests/ado-testsuite.adb
----------------------------------------------------------------------- -- ado-testsuite -- Testsuite for ADO -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Tests; with ADO.Drivers.Tests; with ADO.Sequences.Tests; with ADO.Schemas.Tests; with ADO.Objects.Tests; with ADO.Queries.Tests; with ADO.Parameters.Tests; with ADO.Datasets.Tests; with ADO.Statements.Tests; package body ADO.Testsuite is use ADO.Tests; procedure Drivers (Suite : in Util.Tests.Access_Test_Suite); procedure Drivers (Suite : in Util.Tests.Access_Test_Suite) is separate; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin ADO.Drivers.Tests.Add_Tests (Ret); ADO.Parameters.Tests.Add_Tests (Ret); ADO.Sequences.Tests.Add_Tests (Ret); ADO.Objects.Tests.Add_Tests (Ret); ADO.Statements.Tests.Add_Tests (Ret); ADO.Tests.Add_Tests (Ret); ADO.Schemas.Tests.Add_Tests (Ret); Drivers (Ret); ADO.Queries.Tests.Add_Tests (Ret); ADO.Datasets.Tests.Add_Tests (Ret); return Ret; end Suite; end ADO.Testsuite;
----------------------------------------------------------------------- -- ado-testsuite -- Testsuite for ADO -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Tests; with ADO.Drivers.Tests; with ADO.Sequences.Tests; with ADO.Schemas.Tests; with ADO.Objects.Tests; with ADO.Queries.Tests; with ADO.Parameters.Tests; with ADO.Datasets.Tests; with ADO.Statements.Tests; package body ADO.Testsuite is procedure Drivers (Suite : in Util.Tests.Access_Test_Suite); procedure Drivers (Suite : in Util.Tests.Access_Test_Suite) is separate; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin ADO.Drivers.Tests.Add_Tests (Ret); ADO.Parameters.Tests.Add_Tests (Ret); ADO.Sequences.Tests.Add_Tests (Ret); ADO.Objects.Tests.Add_Tests (Ret); ADO.Statements.Tests.Add_Tests (Ret); ADO.Tests.Add_Tests (Ret); ADO.Schemas.Tests.Add_Tests (Ret); Drivers (Ret); ADO.Queries.Tests.Add_Tests (Ret); ADO.Datasets.Tests.Add_Tests (Ret); return Ret; end Suite; end ADO.Testsuite;
Remove unecessary use clause
Remove unecessary use clause
Ada
apache-2.0
stcarrez/ada-ado
1545d2b30efb2597bdd1177c89c6f36f70f8977d
regtests/util-serialize-io-csv-tests.adb
regtests/util-serialize-io-csv-tests.adb
----------------------------------------------------------------------- -- serialize-io-csv-tests -- Unit tests for CSV parser -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Files; with Util.Serialize.Mappers.Tests; with Util.Serialize.IO.JSON.Tests; package body Util.Serialize.IO.CSV.Tests is package Caller is new Util.Test_Caller (Test, "Serialize.IO.CSV"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.CSV.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.CSV.Write", Test_Output'Access); end Add_Tests; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is use Util.Serialize.Mappers.Tests; procedure Check_Parse (Content : in String; Expect : in Integer); Mapping : aliased Util.Serialize.Mappers.Tests.Map_Test_Mapper.Mapper; Vector_Mapper : aliased Util.Serialize.Mappers.Tests.Map_Test_Vector_Mapper.Mapper; procedure Check_Parse (Content : in String; Expect : in Integer) is P : Parser; Value : aliased Map_Test_Vector.Vector; Mapper : Util.Serialize.Mappers.Processing; begin Mapper.Add_Mapping ("", Vector_Mapper'Unchecked_Access); Map_Test_Vector_Mapper.Set_Context (Mapper, Value'Unchecked_Access); P.Parse_String (Content, Mapper); T.Assert (not P.Has_Error, "Parse error for: " & Content); Util.Tests.Assert_Equals (T, 1, Integer (Value.Length), "Invalid result length"); Util.Tests.Assert_Equals (T, Expect, Integer (Value.Element (1).Value), "Invalid value"); end Check_Parse; HDR : constant String := "name,status,value,bool" & ASCII.CR & ASCII.LF; begin Mapping.Add_Mapping ("name", FIELD_NAME); Mapping.Add_Mapping ("value", FIELD_VALUE); Mapping.Add_Mapping ("status", FIELD_BOOL); Mapping.Add_Mapping ("bool", FIELD_BOOL); Vector_Mapper.Set_Mapping (Mapping'Unchecked_Access); Check_Parse (HDR & "joe,false,23,true", 23); Check_Parse (HDR & "billy,false,""12"",true", 12); Check_Parse (HDR & """John Potter"",false,""1234"",true", 1234); Check_Parse (HDR & """John" & ASCII.CR & "Potter"",False,""3234"",True", 3234); Check_Parse (HDR & """John" & ASCII.LF & "Potter"",False,""3234"",True", 3234); end Test_Parser; -- ------------------------------ -- Test the CSV output stream generation. -- ------------------------------ procedure Test_Output (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Stream : Util.Serialize.IO.CSV.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.csv"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.csv"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Stream.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000); Util.Serialize.IO.JSON.Tests.Write_Stream (Stream); Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "CSV output serialization"); end Test_Output; end Util.Serialize.IO.CSV.Tests;
----------------------------------------------------------------------- -- serialize-io-csv-tests -- Unit tests for CSV parser -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Files; with Util.Serialize.Mappers.Tests; with Util.Serialize.IO.JSON.Tests; package body Util.Serialize.IO.CSV.Tests is package Caller is new Util.Test_Caller (Test, "Serialize.IO.CSV"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.CSV.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.CSV.Write", Test_Output'Access); end Add_Tests; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is use Util.Serialize.Mappers.Tests; procedure Check_Parse (Content : in String; Expect : in Integer); Mapping : aliased Util.Serialize.Mappers.Tests.Map_Test_Mapper.Mapper; Vector_Mapper : aliased Util.Serialize.Mappers.Tests.Map_Test_Vector_Mapper.Mapper; procedure Check_Parse (Content : in String; Expect : in Integer) is P : Parser; Value : aliased Map_Test_Vector.Vector; Mapper : Util.Serialize.Mappers.Processing; begin Mapper.Add_Mapping ("", Vector_Mapper'Unchecked_Access); Map_Test_Vector_Mapper.Set_Context (Mapper, Value'Unchecked_Access); P.Parse_String (Content, Mapper); T.Assert (not P.Has_Error, "Parse error for: " & Content); Util.Tests.Assert_Equals (T, 1, Integer (Value.Length), "Invalid result length"); Util.Tests.Assert_Equals (T, Expect, Integer (Value.Element (1).Value), "Invalid value"); end Check_Parse; HDR : constant String := "name,status,value,bool" & ASCII.CR & ASCII.LF; begin Mapping.Add_Mapping ("name", FIELD_NAME); Mapping.Add_Mapping ("value", FIELD_VALUE); Mapping.Add_Mapping ("status", FIELD_BOOL); Mapping.Add_Mapping ("bool", FIELD_BOOL); Vector_Mapper.Set_Mapping (Mapping'Unchecked_Access); Check_Parse (HDR & "joe,false,23,true", 23); Check_Parse (HDR & "billy,false,""12"",true", 12); Check_Parse (HDR & """John Potter"",false,""1234"",true", 1234); Check_Parse (HDR & """John" & ASCII.CR & "Potter"",False,""3234"",True", 3234); Check_Parse (HDR & """John" & ASCII.LF & "Potter"",False,""3234"",True", 3234); end Test_Parser; -- ------------------------------ -- Test the CSV output stream generation. -- ------------------------------ procedure Test_Output (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Stream : Util.Serialize.IO.CSV.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.csv"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.csv"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Stream.Initialize (Output => File'Unchecked_Access, Size => 10000); Util.Serialize.IO.JSON.Tests.Write_Stream (Stream); Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "CSV output serialization"); end Test_Output; end Util.Serialize.IO.CSV.Tests;
Update Print_Stream initialization
Update Print_Stream initialization
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
08d3c64771b32d9accf13afb99542125c2ff8070
src/asf-models-selects.adb
src/asf-models-selects.adb
----------------------------------------------------------------------- -- asf-models-selects -- Data model for UISelectOne and UISelectMany -- 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.Characters.Conversions; package body ASF.Models.Selects is -- ------------------------------ -- Return an Object from the select item record. -- Returns a NULL object if the item is empty. -- ------------------------------ function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object is begin if Item.Item.Is_Null then return Util.Beans.Objects.Null_Object; else declare Bean : constant Select_Item_Access := new Select_Item; begin Bean.all := Item; return Util.Beans.Objects.To_Object (Bean.all'Access); end; end if; end To_Object; -- ------------------------------ -- Return the <b>Select_Item</b> instance from a generic bean object. -- Returns an empty item if the object does not hold a <b>Select_Item</b>. -- ------------------------------ function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item is Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Object); Result : Select_Item; begin if Bean = null then return Result; end if; if not (Bean.all in Select_Item'Class) then return Result; end if; Result := Select_Item (Bean.all); return Result; end To_Select_Item; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label and value. -- ------------------------------ function Create_Select_Item (Label : in String; Value : in String; Description : in String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is use Ada.Characters.Conversions; Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin Item.Label := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Label)); Item.Value := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Value)); Item.Description := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Description)); Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label and value. -- ------------------------------ function Create_Select_Item_Wide (Label : in Wide_Wide_String; Value : in Wide_Wide_String; Description : in Wide_Wide_String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin Item.Label := To_Unbounded_Wide_Wide_String (Label); Item.Value := To_Unbounded_Wide_Wide_String (Value); Item.Description := To_Unbounded_Wide_Wide_String (Description); Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item_Wide; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label, value and description. -- The objects are converted to a wide wide string. The empty string is used if they -- are null. -- ------------------------------ function Create_Select_Item (Label : in Util.Beans.Objects.Object; Value : in Util.Beans.Objects.Object; Description : in Util.Beans.Objects.Object; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is use Util.Beans.Objects; Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin if not Is_Null (Label) then Item.Label := To_Unbounded_Wide_Wide_String (Label); end if; if not Is_Null (Value) then Item.Value := To_Unbounded_Wide_Wide_String (Value); end if; if not Is_Null (Description) then Item.Description := To_Unbounded_Wide_Wide_String (Description); end if; Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item; -- ------------------------------ -- Get the item label. -- ------------------------------ function Get_Label (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Label); end if; end Get_Label; -- ------------------------------ -- Get the item value. -- ------------------------------ function Get_Value (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Value); end if; end Get_Value; -- ------------------------------ -- Get the item description. -- ------------------------------ function Get_Description (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Description); end if; end Get_Description; -- ------------------------------ -- Returns true if the item is disabled. -- ------------------------------ function Is_Disabled (Item : in Select_Item) return Boolean is begin if Item.Item.Is_Null then return False; else return Item.Item.Value.Disabled; end if; end Is_Disabled; -- ------------------------------ -- Returns true if the label must be escaped using HTML escape rules. -- ------------------------------ function Is_Escaped (Item : in Select_Item) return Boolean is begin if Item.Item.Is_Null then return False; else return Item.Item.Value.Escape; end if; end Is_Escaped; -- ------------------------------ -- Returns true if the select item component is empty. -- ------------------------------ function Is_Empty (Item : in Select_Item) return Boolean is begin return Item.Item.Is_Null; end Is_Empty; -- ------------------------------ -- 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 Select_Item; Name : in String) return Util.Beans.Objects.Object is begin if From.Item.Is_Null then return Util.Beans.Objects.Null_Object; end if; declare Item : constant Select_Item_Record_Access := From.Item.Value; begin if Name = "name" then return Util.Beans.Objects.To_Object (Item.Label); elsif Name = "value" then return Util.Beans.Objects.To_Object (Item.Value); elsif Name = "description" then return Util.Beans.Objects.To_Object (Item.Description); elsif Name = "disabled" then return Util.Beans.Objects.To_Object (Item.Disabled); elsif Name = "escaped" then return Util.Beans.Objects.To_Object (Item.Escape); else return Util.Beans.Objects.Null_Object; end if; end; end Get_Value; -- ------------------------------ -- Select Item List -- ------------------------------ -- ------------------------------ -- Return an Object from the select item list. -- Returns a NULL object if the list is empty. -- ------------------------------ function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object is begin if Item.List.Is_Null then return Util.Beans.Objects.Null_Object; else declare Bean : constant Select_Item_List_Access := new Select_Item_List; begin Bean.all := Item; return Util.Beans.Objects.To_Object (Bean.all'Access); end; end if; end To_Object; -- ------------------------------ -- Return the <b>Select_Item_List</b> instance from a generic bean object. -- Returns an empty list if the object does not hold a <b>Select_Item_List</b>. -- ------------------------------ function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List is Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Object); Result : Select_Item_List; begin if Bean = null then return Result; end if; if not (Bean.all in Select_Item_List'Class) then return Result; end if; Result := Select_Item_List (Bean.all); return Result; end To_Select_Item_List; -- ------------------------------ -- Get the number of items in the list. -- ------------------------------ function Length (List : in Select_Item_List) return Natural is begin if List.List.Is_Null then return 0; else return Natural (List.List.Value.List.Length); end if; end Length; -- ------------------------------ -- Get the select item from the list -- ------------------------------ function Get_Select_Item (List : in Select_Item_List'Class; Pos : in Positive) return Select_Item is begin if List.List.Is_Null then raise Constraint_Error with "Select item list is empty"; end if; return List.List.Value.List.Element (Pos); end Get_Select_Item; -- ------------------------------ -- Add the item at the end of the list. -- ------------------------------ procedure Append (List : in out Select_Item_List; Item : in Select_Item'Class) is begin if List.List.Is_Null then List.List := Select_Item_Vector_Refs.Create; end if; List.List.Value.all.List.Append (Select_Item (Item)); end Append; -- ------------------------------ -- Add the item at the end of the list. This is a shortcut for -- Append (Create_List_Item (Label, Value)) -- ------------------------------ procedure Append (List : in out Select_Item_List; Label : in String; Value : in String) is begin List.Append (Create_Select_Item (Label, Value)); end Append; -- ------------------------------ -- 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 Select_Item_List; Name : in String) return Util.Beans.Objects.Object is begin return Util.Beans.Objects.Null_Object; end Get_Value; end ASF.Models.Selects;
----------------------------------------------------------------------- -- asf-models-selects -- Data model for UISelectOne and UISelectMany -- 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.Characters.Conversions; package body ASF.Models.Selects is -- ------------------------------ -- Return an Object from the select item record. -- Returns a NULL object if the item is empty. -- ------------------------------ function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object is begin if Item.Item.Is_Null then return Util.Beans.Objects.Null_Object; else declare Bean : constant Select_Item_Access := new Select_Item; begin Bean.all := Item; return Util.Beans.Objects.To_Object (Bean.all'Access); end; end if; end To_Object; -- ------------------------------ -- Return the <b>Select_Item</b> instance from a generic bean object. -- Returns an empty item if the object does not hold a <b>Select_Item</b>. -- ------------------------------ function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item is Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Object); Result : Select_Item; begin if Bean = null then return Result; end if; if not (Bean.all in Select_Item'Class) then return Result; end if; Result := Select_Item (Bean.all); return Result; end To_Select_Item; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label and value. -- ------------------------------ function Create_Select_Item (Label : in String; Value : in String; Description : in String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is use Ada.Characters.Conversions; Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin Item.Label := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Label)); Item.Value := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Value)); Item.Description := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Description)); Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label and value. -- ------------------------------ function Create_Select_Item_Wide (Label : in Wide_Wide_String; Value : in Wide_Wide_String; Description : in Wide_Wide_String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin Item.Label := To_Unbounded_Wide_Wide_String (Label); Item.Value := To_Unbounded_Wide_Wide_String (Value); Item.Description := To_Unbounded_Wide_Wide_String (Description); Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item_Wide; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label, value and description. -- The objects are converted to a wide wide string. The empty string is used if they -- are null. -- ------------------------------ function Create_Select_Item (Label : in Util.Beans.Objects.Object; Value : in Util.Beans.Objects.Object; Description : in Util.Beans.Objects.Object; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is use Util.Beans.Objects; Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin if not Is_Null (Label) then Item.Label := To_Unbounded_Wide_Wide_String (Label); end if; if not Is_Null (Value) then Item.Value := To_Unbounded_Wide_Wide_String (Value); end if; if not Is_Null (Description) then Item.Description := To_Unbounded_Wide_Wide_String (Description); end if; Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item; -- ------------------------------ -- Get the item label. -- ------------------------------ function Get_Label (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Label); end if; end Get_Label; -- ------------------------------ -- Get the item value. -- ------------------------------ function Get_Value (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Value); end if; end Get_Value; -- ------------------------------ -- Get the item description. -- ------------------------------ function Get_Description (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Description); end if; end Get_Description; -- ------------------------------ -- Returns true if the item is disabled. -- ------------------------------ function Is_Disabled (Item : in Select_Item) return Boolean is begin if Item.Item.Is_Null then return False; else return Item.Item.Value.Disabled; end if; end Is_Disabled; -- ------------------------------ -- Returns true if the label must be escaped using HTML escape rules. -- ------------------------------ function Is_Escaped (Item : in Select_Item) return Boolean is begin if Item.Item.Is_Null then return False; else return Item.Item.Value.Escape; end if; end Is_Escaped; -- ------------------------------ -- Returns true if the select item component is empty. -- ------------------------------ function Is_Empty (Item : in Select_Item) return Boolean is begin return Item.Item.Is_Null; end Is_Empty; -- ------------------------------ -- 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 Select_Item; Name : in String) return Util.Beans.Objects.Object is begin if From.Item.Is_Null then return Util.Beans.Objects.Null_Object; end if; declare Item : constant Select_Item_Record_Access := From.Item.Value; begin if Name = "name" then return Util.Beans.Objects.To_Object (Item.Label); elsif Name = "value" then return Util.Beans.Objects.To_Object (Item.Value); elsif Name = "description" then return Util.Beans.Objects.To_Object (Item.Description); elsif Name = "disabled" then return Util.Beans.Objects.To_Object (Item.Disabled); elsif Name = "escaped" then return Util.Beans.Objects.To_Object (Item.Escape); else return Util.Beans.Objects.Null_Object; end if; end; end Get_Value; -- ------------------------------ -- Select Item List -- ------------------------------ -- ------------------------------ -- Return an Object from the select item list. -- Returns a NULL object if the list is empty. -- ------------------------------ function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object is begin if Item.List.Is_Null then return Util.Beans.Objects.Null_Object; else declare Bean : constant Select_Item_List_Access := new Select_Item_List; begin Bean.all := Item; return Util.Beans.Objects.To_Object (Bean.all'Access); end; end if; end To_Object; -- ------------------------------ -- Return the <b>Select_Item_List</b> instance from a generic bean object. -- Returns an empty list if the object does not hold a <b>Select_Item_List</b>. -- ------------------------------ function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List is Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Object); Result : Select_Item_List; begin if Bean = null then return Result; end if; if not (Bean.all in Select_Item_List'Class) then return Result; end if; Result := Select_Item_List (Bean.all); return Result; end To_Select_Item_List; -- ------------------------------ -- Get the number of items in the list. -- ------------------------------ function Length (List : in Select_Item_List) return Natural is begin if List.List.Is_Null then return 0; else return Natural (List.List.Value.List.Length); end if; end Length; -- ------------------------------ -- Get the select item from the list -- ------------------------------ function Get_Select_Item (List : in Select_Item_List'Class; Pos : in Positive) return Select_Item is begin if List.List.Is_Null then raise Constraint_Error with "Select item list is empty"; end if; return List.List.Value.List.Element (Pos); end Get_Select_Item; -- ------------------------------ -- Add the item at the end of the list. -- ------------------------------ procedure Append (List : in out Select_Item_List; Item : in Select_Item'Class) is begin if List.List.Is_Null then List.List := Select_Item_Vector_Refs.Create; end if; List.List.Value.all.List.Append (Select_Item (Item)); end Append; -- ------------------------------ -- Add the item at the end of the list. This is a shortcut for -- Append (Create_List_Item (Label, Value)) -- ------------------------------ procedure Append (List : in out Select_Item_List; Label : in String; Value : in String) is begin List.Append (Create_Select_Item (Label, Value)); end Append; -- ------------------------------ -- 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 Select_Item_List; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; end ASF.Models.Selects;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf