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
7bc87a508b873a29d8dd3b2fd3fdb2b4d1f76431
awa/plugins/awa-images/src/awa-images-services.adb
awa/plugins/awa-images/src/awa-images-services.adb
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 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.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with ADO; with ADO.Sessions; with AWA.Images.Models; with AWA.Services.Contexts; with AWA.Storages.Services; with AWA.Storages.Modules; with Ada.Strings.Unbounded; with EL.Variables.Default; with EL.Contexts.Default; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package body AWA.Images.Services is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Image Service -- ------------------------------ Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services"); -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); declare Ctx : EL.Contexts.Default.Default_Context; Command : constant String := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); begin Service.Thumbnail_Command := EL.Expressions.Create_Expression (Command, Ctx); exception when E : others => Log.Error ("Invalid thumbnail command: ", E, True); end; end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (File); Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File; Local_File : AWA.Storages.Storage_File; Width : Natural; Height : Natural; begin Img.Load (DB, Id); Storage_Service.Get_Local_File (From => Img.Get_Storage.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Ctx.Start; Img.Save (DB); -- Storage_Service.Save (Target_File); Ctx.Commit; end Build_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Service); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Ctx.Start; Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Save (DB); Ctx.Commit; end Create_Image; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; end AWA.Images.Services;
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 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.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with ADO; with ADO.Sessions; with AWA.Images.Models; with AWA.Services.Contexts; with AWA.Storages.Services; with AWA.Storages.Modules; with Ada.Strings.Unbounded; with EL.Variables.Default; with EL.Contexts.Default; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package body AWA.Images.Services is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Image Service -- ------------------------------ Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services"); -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); Service.Thumbnail_Command := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (File); Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File; Local_File : AWA.Storages.Storage_File; Width : Natural; Height : Natural; begin Img.Load (DB, Id); Storage_Service.Get_Local_File (From => Img.Get_Storage.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Ctx.Start; Img.Save (DB); -- Storage_Service.Save (Target_File); Ctx.Commit; end Build_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Service); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Ctx.Start; Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Save (DB); Ctx.Commit; end Create_Image; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; end AWA.Images.Services;
Use the Get_Config procedure that returns an EL expression to get the thumbnail command
Use the Get_Config procedure that returns an EL expression to get the thumbnail command
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1d05516e6cb19211fa59f6f059482bdfd10c20ab
awa/plugins/awa-jobs/src/awa-jobs-services.ads
awa/plugins/awa-jobs/src/awa-jobs-services.ads
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Maps; with ADO.Sessions; with AWA.Events; with AWA.Jobs.Models; package AWA.Jobs.Services is Closed_Error : exception; Schedule_Error : exception; Execute_Error : exception; Invalid_Value : exception; -- Event posted when a job is created. package Job_Create_Event is new AWA.Events.Definition (Name => "job-create"); -- Get the job status. function Get_Job_Status (Id : in ADO.Identifier) return AWA.Jobs.Models.Job_Status_Type; -- ------------------------------ -- Abstract_Job Type -- ------------------------------ -- The <b>Abstract_Job_Type</b> is an abstract tagged record which defines a job that can be -- scheduled and executed. type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Abstract_Job_Access is access all Abstract_Job_Type'Class; -- Execute the job. This operation must be implemented and should perform the work -- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve -- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result. procedure Execute (Job : in out Abstract_Job_Type) is abstract; -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String); -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Integer); -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String; -- Get the job parameter identified by the <b>Name</b> and convert the value as an integer. -- If the parameter is not defined, return the default value passed in <b>Default</b>. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String; Default : in Integer) return Integer; -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object; -- Get the job status. function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type; -- Get the job identifier once the job was scheduled. The job identifier allows to -- retrieve the job and check its execution and completion status later on. function Get_Identifier (Job : in Abstract_Job_Type) return ADO.Identifier; -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type); -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class); -- ------------------------------ -- Job Factory -- ------------------------------ -- The <b>Job_Factory</b> is the interface that allows to create a job instance in order -- to execute a scheduled job. type Job_Factory is abstract tagged limited null record; type Job_Factory_Access is access all Job_Factory'Class; -- Create the job instance using the job factory. function Create (Factory : in Job_Factory) return Abstract_Job_Access is abstract; -- Get the job factory name. function Get_Name (Factory : in Job_Factory'Class) return String; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class); -- ------------------------------ -- Work Factory -- ------------------------------ type Work_Access is access procedure (Job : in out Abstract_Job_Type'Class); type Work_Factory (Work : Work_Access) is new Job_Factory with null record; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access; -- ------------------------------ -- -- ------------------------------ type Job_Type is new Abstract_Job_Type with private; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class); procedure Execute (Job : in out Job_Type); -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. generic type T is new Abstract_Job_Type with private; package Definition is type Job_Type_Factory is new Job_Factory with null record; overriding function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access; Factory : aliased Job_Type_Factory; end Definition; generic Work : in Work_Access; package Work_Definition is type S_Factory is new Work_Factory with null record; Factory : aliased S_Factory := S_Factory '(Work => Work); end Work_Definition; -- Execute the job associated with the given event. procedure Execute (Event : in AWA.Events.Module_Event'Class); private -- Execute the job and save the job information in the database. procedure Execute (Job : in out Abstract_Job_Type'Class; DB : in out ADO.Sessions.Master_Session'Class); type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with record Job : AWA.Jobs.Models.Job_Ref; Props : Util.Beans.Objects.Maps.Map; Results : Util.Beans.Objects.Maps.Map; Props_Modified : Boolean := False; Results_Modified : Boolean := False; end record; type Job_Type is new Abstract_Job_Type with record Work : Work_Access; end record; end AWA.Jobs.Services;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Maps; with ADO.Sessions; with AWA.Events; with AWA.Jobs.Models; package AWA.Jobs.Services is Closed_Error : exception; Schedule_Error : exception; Execute_Error : exception; Invalid_Value : exception; -- Event posted when a job is created. package Job_Create_Event is new AWA.Events.Definition (Name => "job-create"); -- Get the job status. function Get_Job_Status (Id : in ADO.Identifier) return AWA.Jobs.Models.Job_Status_Type; -- ------------------------------ -- Abstract_Job Type -- ------------------------------ -- The <b>Abstract_Job_Type</b> is an abstract tagged record which defines a job that can be -- scheduled and executed. type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Abstract_Job_Access is access all Abstract_Job_Type'Class; -- Execute the job. This operation must be implemented and should perform the work -- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve -- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result. procedure Execute (Job : in out Abstract_Job_Type) is abstract; -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String); -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Integer); -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String; -- Get the job parameter identified by the <b>Name</b> and convert the value as an integer. -- If the parameter is not defined, return the default value passed in <b>Default</b>. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String; Default : in Integer) return Integer; -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object; -- Get the job status. function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type; -- Get the job identifier once the job was scheduled. The job identifier allows to -- retrieve the job and check its execution and completion status later on. function Get_Identifier (Job : in Abstract_Job_Type) return ADO.Identifier; -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type); -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class); -- ------------------------------ -- Job Factory -- ------------------------------ -- The <b>Job_Factory</b> is the interface that allows to create a job instance in order -- to execute a scheduled job. type Job_Factory is abstract tagged limited null record; type Job_Factory_Access is access all Job_Factory'Class; -- Create the job instance using the job factory. function Create (Factory : in Job_Factory) return Abstract_Job_Access is abstract; -- Get the job factory name. function Get_Name (Factory : in Job_Factory'Class) return String; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class); -- ------------------------------ -- Work Factory -- ------------------------------ type Work_Access is access procedure (Job : in out Abstract_Job_Type'Class); type Work_Factory (Work : Work_Access) is new Job_Factory with null record; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access; -- ------------------------------ -- -- ------------------------------ type Job_Type is new Abstract_Job_Type with private; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class); procedure Execute (Job : in out Job_Type); -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. generic type T is new Abstract_Job_Type with private; package Definition is type Job_Type_Factory is new Job_Factory with null record; overriding function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access; -- The job factory. Factory : constant Job_Factory_Access; private Instance : aliased Job_Type_Factory; Factory : constant Job_Factory_Access := Instance'Access; end Definition; generic Work : in Work_Access; package Work_Definition is type S_Factory is new Work_Factory with null record; -- The job factory. Factory : constant Job_Factory_Access; private Instance : aliased S_Factory := S_Factory '(Work => Work); Factory : constant Job_Factory_Access := Instance'Access; end Work_Definition; -- Execute the job associated with the given event. procedure Execute (Event : in AWA.Events.Module_Event'Class); private -- Execute the job and save the job information in the database. procedure Execute (Job : in out Abstract_Job_Type'Class; DB : in out ADO.Sessions.Master_Session'Class); type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with record Job : AWA.Jobs.Models.Job_Ref; Props : Util.Beans.Objects.Maps.Map; Results : Util.Beans.Objects.Maps.Map; Props_Modified : Boolean := False; Results_Modified : Boolean := False; end record; type Job_Type is new Abstract_Job_Type with record Work : Work_Access; end record; end AWA.Jobs.Services;
Simplify the use of the job factory
Simplify the use of the job factory
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
86c070d14ef41fd0393cb49e779b16863078aaa2
src/orka/interface/orka-rendering-framebuffers.ads
src/orka/interface/orka-rendering-framebuffers.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Ada.Containers.Indefinite_Holders; with GL.Buffers; with GL.Objects.Framebuffers; with GL.Objects.Textures; with GL.Types.Colors; with Orka.Contexts; with Orka.Rendering.Buffers; with Orka.Rendering.Textures; with Orka.Windows; package Orka.Rendering.Framebuffers is pragma Preelaborate; use GL.Types; package FB renames GL.Objects.Framebuffers; package Textures renames GL.Objects.Textures; subtype Color_Attachment_Point is FB.Attachment_Point range FB.Color_Attachment_0 .. FB.Color_Attachment_15; type Use_Point_Array is array (Rendering.Framebuffers.Color_Attachment_Point) of Boolean; -- TODO Use as formal parameter in procedure Invalidate type Buffer_Values is record Color : Colors.Color := (0.0, 0.0, 0.0, 0.0); Depth : GL.Buffers.Depth := 1.0; Stencil : GL.Buffers.Stencil_Index := 0; end record; type Framebuffer (Default : Boolean; Width, Height, Samples : Size) is tagged private with Type_Invariant => (if Framebuffer.Default then Framebuffer.Samples = 0); type Framebuffer_Ptr is not null access Framebuffer; function Create_Framebuffer (Width, Height, Samples : Size; Context : Contexts.Context'Class) return Framebuffer with Pre => (if Samples > 0 then Context.Enabled (Contexts.Multisample)), Post => not Create_Framebuffer'Result.Default; function Create_Framebuffer (Width, Height : Size) return Framebuffer with Post => not Create_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function Get_Default_Framebuffer (Window : Orka.Windows.Window'Class) return Framebuffer with Post => Get_Default_Framebuffer'Result.Default; function Create_Default_Framebuffer (Width, Height : Size) return Framebuffer with Post => Create_Default_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function GL_Framebuffer (Object : Framebuffer) return FB.Framebuffer with Inline; ----------------------------------------------------------------------------- function Image (Object : Framebuffer) return String; -- Return a description of the given framebuffer procedure Use_Framebuffer (Object : Framebuffer); -- Use the framebuffer during rendering -- -- The viewport is adjusted to the size of the framebuffer. procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values); -- Set the default values for the color buffers and depth and stencil -- buffers function Default_Values (Object : Framebuffer) return Buffer_Values; -- Return the current default values used when clearing the attached -- textures procedure Set_Read_Buffer (Object : Framebuffer; Buffer : GL.Buffers.Color_Buffer_Selector); -- Set the buffer to use when blitting to another framebuffer with -- procedure Resolve_To procedure Set_Draw_Buffers (Object : in out Framebuffer; Buffers : GL.Buffers.Color_Buffer_List); -- Set the buffers to use when drawing to output variables in a fragment -- shader, when calling procedure Clear, or when another framebuffer -- blits its read buffer to this framebuffer with procedure Resolve_To procedure Clear (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (others => True)); -- Clear the attached textures for which the mask is True using -- the default values set with Set_Default_Values -- -- For clearing to be effective, the following conditions must apply: -- -- - Write mask off -- - Rasterizer discard disabled -- - Scissor test off or scissor rectangle set to the desired region -- - Called procedure Set_Draw_Buffers with a list of attachments -- -- If a combined depth/stencil texture has been attached, the depth -- and stencil components can be cleared separately, but it may be -- faster to clear both components. procedure Invalidate (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits); -- Invalidate the attached textures for which the mask is True procedure Resolve_To (Object, Subject : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False)) with Pre => Object /= Subject and (Mask.Color or Mask.Depth or Mask.Stencil) and (if Object.Samples > 0 and Subject.Samples > 0 then Object.Samples = Subject.Samples); -- Copy one or more buffers, resolving multiple samples and scaling -- if necessary, from the source to the destination framebuffer -- -- If a buffer is specified in the mask, then the buffer should exist -- in both framebuffers, otherwise the buffer is not copied. Call -- Set_Read_Buffer and Set_Draw_Buffers to control which buffer is read -- from and which buffers are written to. -- -- Format of color buffers may differ and will be converted (if -- supported). Formats of depth and stencil buffers must match. -- -- Note: simultaneously resolving multiple samples and scaling -- requires GL_EXT_framebuffer_multisample_blit_scaled. procedure Attach (Object : in out Framebuffer; Attachment : FB.Attachment_Point; Texture : Textures.Texture; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and (if Attachment in Color_Attachment_Point then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => Object.Has_Attachment (Attachment); -- Attach the texture to the attachment point -- -- The internal format of the texture must be valid for the given -- attachment point. procedure Attach (Object : in out Framebuffer; Texture : Textures.Texture; Level : Textures.Mipmap_Level := 0); -- Attach the texture to an attachment point based on the internal -- format of the texture -- -- Internally calls the procedure Attach above. -- -- If the texture is color renderable, it will always be attached to -- Color_Attachment_0. If you need to attach a texture to a different -- color attachment point then use the other procedure Attach directly. -- -- If the texture is layered and you want to attach a specific layer, -- then you must call the procedure Attach_Layer below instead. procedure Attach_Layer (Object : in out Framebuffer; Attachment : FB.Attachment_Point; Texture : Textures.Texture; Layer : Natural; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and Texture.Layered and (if Attachment in Color_Attachment_Point then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach layer of " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => Object.Has_Attachment (Attachment); -- Attach the selected 1D/2D layer of the texture to the attachment point -- -- The internal format of the texture must be valid for the given -- attachment point. -- -- The texture must be layered (3D, 1D/2D array, cube -- map [array], or 2D multisampled array). procedure Detach (Object : in out Framebuffer; Attachment : FB.Attachment_Point) with Pre => not Object.Default, Post => not Object.Has_Attachment (Attachment); -- Detach any texture currently attached to the given attachment point function Has_Attachment (Object : Framebuffer; Attachment : FB.Attachment_Point) return Boolean; Framebuffer_Incomplete_Error : exception; private package Attachment_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => Textures.Texture, "=" => Textures."="); package Color_Buffer_List_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => GL.Buffers.Color_Buffer_List, "=" => GL.Buffers."="); type Attachment_Array is array (FB.Attachment_Point) of Attachment_Holder.Holder; type Framebuffer (Default : Boolean; Width, Height, Samples : Size) is tagged record GL_Framebuffer : FB.Framebuffer; Attachments : Attachment_Array; Defaults : Buffer_Values; Draw_Buffers : Color_Buffer_List_Holder.Holder; end record; end Orka.Rendering.Framebuffers;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Ada.Containers.Indefinite_Holders; with GL.Buffers; with GL.Objects.Framebuffers; with GL.Objects.Textures; with GL.Types.Colors; with Orka.Contexts; with Orka.Rendering.Buffers; with Orka.Rendering.Textures; with Orka.Windows; package Orka.Rendering.Framebuffers is pragma Preelaborate; use GL.Types; package FB renames GL.Objects.Framebuffers; package Textures renames GL.Objects.Textures; subtype Color_Attachment_Point is FB.Attachment_Point range FB.Color_Attachment_0 .. FB.Color_Attachment_15; type Use_Point_Array is array (Rendering.Framebuffers.Color_Attachment_Point) of Boolean; -- TODO Use as formal parameter in procedure Invalidate type Buffer_Values is record Color : Colors.Color := (0.0, 0.0, 0.0, 0.0); Depth : GL.Buffers.Depth := 1.0; Stencil : GL.Buffers.Stencil_Index := 0; end record; type Framebuffer (Default : Boolean; Width, Height, Samples : Size) is tagged private with Type_Invariant => (if Framebuffer.Default then Framebuffer.Samples = 0); type Framebuffer_Ptr is not null access Framebuffer; function Create_Framebuffer (Width, Height, Samples : Size; Context : Contexts.Context'Class) return Framebuffer with Pre => (if Samples > 0 then Context.Enabled (Contexts.Multisample)), Post => not Create_Framebuffer'Result.Default; function Create_Framebuffer (Width, Height : Size) return Framebuffer with Post => not Create_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function Get_Default_Framebuffer (Window : Orka.Windows.Window'Class) return Framebuffer with Post => Get_Default_Framebuffer'Result.Default; function Create_Default_Framebuffer (Width, Height : Size) return Framebuffer with Post => Create_Default_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function GL_Framebuffer (Object : Framebuffer) return FB.Framebuffer with Inline; ----------------------------------------------------------------------------- function Image (Object : Framebuffer) return String; -- Return a description of the given framebuffer procedure Use_Framebuffer (Object : Framebuffer); -- Use the framebuffer during rendering -- -- The viewport is adjusted to the size of the framebuffer. procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values); -- Set the default values for the color buffers and depth and stencil -- buffers function Default_Values (Object : Framebuffer) return Buffer_Values; -- Return the current default values used when clearing the attached -- textures procedure Set_Read_Buffer (Object : Framebuffer; Buffer : GL.Buffers.Color_Buffer_Selector); -- Set the buffer to use when blitting to another framebuffer with -- procedure Resolve_To procedure Set_Draw_Buffers (Object : in out Framebuffer; Buffers : GL.Buffers.Color_Buffer_List); -- Set the buffers to use when drawing to output variables in a fragment -- shader, when calling procedure Clear, or when another framebuffer -- blits its read buffer to this framebuffer with procedure Resolve_To procedure Clear (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (others => True)); -- Clear the attached textures for which the mask is True using -- the default values set with Set_Default_Values -- -- For clearing to be effective, the following conditions must apply: -- -- - Write mask off -- - Rasterizer discard disabled -- - Scissor test off or scissor rectangle set to the desired region -- - Called procedure Set_Draw_Buffers with a list of attachments -- -- If a combined depth/stencil texture has been attached, the depth -- and stencil components can be cleared separately, but it may be -- faster to clear both components. procedure Invalidate (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits); -- Invalidate the attached textures for which the mask is True procedure Resolve_To (Object, Subject : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False)) with Pre => Object /= Subject and (Mask.Color or Mask.Depth or Mask.Stencil) and (if Object.Samples > 0 and Subject.Samples > 0 then Object.Samples = Subject.Samples); -- Copy one or more buffers, resolving multiple samples and scaling -- if necessary, from the source to the destination framebuffer -- -- If a buffer is specified in the mask, then the buffer should exist -- in both framebuffers, otherwise the buffer is not copied. Call -- Set_Read_Buffer and Set_Draw_Buffers to control which buffer is read -- from and which buffers are written to. -- -- Format of color buffers may differ and will be converted (if -- supported). Formats of depth and stencil buffers must match. -- -- Note: simultaneously resolving multiple samples and scaling -- requires GL_EXT_framebuffer_multisample_blit_scaled. procedure Attach (Object : in out Framebuffer; Attachment : FB.Attachment_Point; Texture : Textures.Texture; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and (if Attachment in Color_Attachment_Point then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => Object.Has_Attachment (Attachment); -- Attach the texture to the attachment point -- -- The internal format of the texture must be valid for the given -- attachment point. -- -- If one of the attached textures is layered (3D, 1D/2D array, cube -- map [array], or 2D multisampled array), then all attachments must -- have the same kind. -- -- All attachments of the framebuffer must have the same amount of -- samples and they must all have fixed sample locations, or none of -- them must have them. procedure Attach (Object : in out Framebuffer; Texture : Textures.Texture; Level : Textures.Mipmap_Level := 0); -- Attach the texture to an attachment point based on the internal -- format of the texture -- -- Internally calls the procedure Attach above. -- -- If the texture is color renderable, it will always be attached to -- Color_Attachment_0. If you need to attach a texture to a different -- color attachment point then use the other procedure Attach directly. -- -- If the texture is layered and you want to attach a specific layer, -- then you must call the procedure Attach_Layer below instead. procedure Attach_Layer (Object : in out Framebuffer; Attachment : FB.Attachment_Point; Texture : Textures.Texture; Layer : Natural; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and Texture.Layered and (if Attachment in Color_Attachment_Point then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach layer of " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => Object.Has_Attachment (Attachment); -- Attach the selected 1D/2D layer of the texture to the attachment point -- -- The internal format of the texture must be valid for the given -- attachment point. -- -- The texture must be layered (3D, 1D/2D array, cube -- map [array], or 2D multisampled array). procedure Detach (Object : in out Framebuffer; Attachment : FB.Attachment_Point) with Pre => not Object.Default, Post => not Object.Has_Attachment (Attachment); -- Detach any texture currently attached to the given attachment point function Has_Attachment (Object : Framebuffer; Attachment : FB.Attachment_Point) return Boolean; Framebuffer_Incomplete_Error : exception; private package Attachment_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => Textures.Texture, "=" => Textures."="); package Color_Buffer_List_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => GL.Buffers.Color_Buffer_List, "=" => GL.Buffers."="); type Attachment_Array is array (FB.Attachment_Point) of Attachment_Holder.Holder; type Framebuffer (Default : Boolean; Width, Height, Samples : Size) is tagged record GL_Framebuffer : FB.Framebuffer; Attachments : Attachment_Array; Defaults : Buffer_Values; Draw_Buffers : Color_Buffer_List_Holder.Holder; end record; end Orka.Rendering.Framebuffers;
Document some framebuffer completion requirements for Attach
orka: Document some framebuffer completion requirements for Attach Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
b904d1191b154909d1abbba7b50f32ef446bcd7a
src/asf-views.ads
src/asf-views.ads
----------------------------------------------------------------------- -- asf-views -- Views -- 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. ----------------------------------------------------------------------- -- The <b>ASF.Views</b> package defines the abstractions to represent -- an XHTML view that can be instantiated to create the JSF component -- tree. The <b>ASF.Views</b> are read only once and they are shared -- by the JSF component trees that are instantiated from it. -- -- The XHTML view is read using a SAX parser which creates nodes -- and attributes to represent the view. -- -- The <b>ASF.Views</b> is composed of nodes represented by <b>Tag_Node</b> -- and attributes represented by <b>Tag_Attribute</b>. In a sense, this -- is very close to an XML DOM tree. package ASF.Views is -- ------------------------------ -- Source line information -- ------------------------------ type File_Info (<>) is limited private; type File_Info_Access is access all File_Info; -- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b> -- and whose relative path portion starts at <b>Relative_Position</b>. function Create_File_Info (Path : in String; Relative_Position : in Natural) return File_Info_Access; -- Get the relative path name function Relative_Path (File : in File_Info) return String; type Line_Info is private; -- Get the line number function Line (Info : in Line_Info) return Natural; pragma Inline (Line); -- Get the source file function File (Info : in Line_Info) return String; pragma Inline (File); private type File_Info (Length : Natural) is limited record Path : String (1 .. Length); Relative_Pos : Natural; end record; NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 0); type Line_Info is record Line : Natural := 0; Column : Natural := 0; File : File_Info_Access := NO_FILE'Access; end record; end ASF.Views;
----------------------------------------------------------------------- -- asf-views -- Views -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>ASF.Views</b> package defines the abstractions to represent -- an XHTML view that can be instantiated to create the JSF component -- tree. The <b>ASF.Views</b> are read only once and they are shared -- by the JSF component trees that are instantiated from it. -- -- The XHTML view is read using a SAX parser which creates nodes -- and attributes to represent the view. -- -- The <b>ASF.Views</b> is composed of nodes represented by <b>Tag_Node</b> -- and attributes represented by <b>Tag_Attribute</b>. In a sense, this -- is very close to an XML DOM tree. package ASF.Views is -- ------------------------------ -- Source line information -- ------------------------------ type File_Info (<>) is limited private; type File_Info_Access is access all File_Info; -- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b> -- and whose relative path portion starts at <b>Relative_Position</b>. function Create_File_Info (Path : in String; Relative_Position : in Natural) return File_Info_Access; -- Get the relative path name function Relative_Path (File : in File_Info) return String; type Line_Info is private; -- Get the line number function Line (Info : in Line_Info) return Natural; pragma Inline (Line); -- Get the source file function File (Info : in Line_Info) return String; pragma Inline (File); private type File_Info (Length : Natural) is limited record Relative_Pos : Natural; Path : String (1 .. Length); end record; NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 0); type Line_Info is record Line : Natural := 0; Column : Natural := 0; File : File_Info_Access := NO_FILE'Access; end record; end ASF.Views;
Reorder the File_Info record
Reorder the File_Info record
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
b3d735f03b948a9fd0f92135e09dac1a6df838ae
src/orka/interface/orka-rendering-framebuffers.ads
src/orka/interface/orka-rendering-framebuffers.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Ada.Containers.Indefinite_Holders; with GL.Buffers; with GL.Objects.Framebuffers; with GL.Objects.Textures; with GL.Types.Colors; with Orka.Contexts; with Orka.Rendering.Buffers; with Orka.Rendering.Textures; with Orka.Windows; package Orka.Rendering.Framebuffers is pragma Preelaborate; use GL.Types; package FB renames GL.Objects.Framebuffers; package Textures renames GL.Objects.Textures; subtype Color_Attachment_Point is FB.Attachment_Point range FB.Color_Attachment_0 .. FB.Color_Attachment_15; type Use_Point_Array is array (Rendering.Framebuffers.Color_Attachment_Point) of Boolean; -- TODO Use as formal parameter in procedure Invalidate type Buffer_Values is record Color : Colors.Color := (0.0, 0.0, 0.0, 0.0); Depth : GL.Buffers.Depth := 1.0; Stencil : GL.Buffers.Stencil_Index := 0; end record; type Framebuffer (Default : Boolean; Width, Height, Samples : Size) is tagged private with Type_Invariant => (if Framebuffer.Default then Framebuffer.Samples = 0); type Framebuffer_Ptr is not null access Framebuffer; function Create_Framebuffer (Width, Height, Samples : Size; Context : Contexts.Context'Class) return Framebuffer with Pre => Samples > 0 and Context.Enabled (Contexts.Multisample), Post => not Create_Framebuffer'Result.Default; function Create_Framebuffer (Width, Height : Size) return Framebuffer with Post => not Create_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function Get_Default_Framebuffer (Window : Orka.Windows.Window'Class) return Framebuffer with Post => Get_Default_Framebuffer'Result.Default; function Create_Default_Framebuffer (Width, Height : Size) return Framebuffer with Post => Create_Default_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function GL_Framebuffer (Object : Framebuffer) return FB.Framebuffer with Inline; ----------------------------------------------------------------------------- function Image (Object : Framebuffer) return String; -- Return a description of the given framebuffer procedure Use_Framebuffer (Object : Framebuffer); -- Use the framebuffer during rendering -- -- The viewport is adjusted to the size of the framebuffer. procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values); -- Set the default values for the color buffers and depth and stencil -- buffers function Default_Values (Object : Framebuffer) return Buffer_Values; -- Return the current default values used when clearing the attached -- textures procedure Set_Read_Buffer (Object : Framebuffer; Buffer : GL.Buffers.Color_Buffer_Selector); -- Set the buffer to use when blitting to another framebuffer with -- procedure Resolve_To procedure Set_Draw_Buffers (Object : in out Framebuffer; Buffers : GL.Buffers.Color_Buffer_List); -- Set the buffers to use when drawing to output variables in a fragment -- shader, when calling procedure Clear, or when another framebuffer -- blits its read buffer to this framebuffer with procedure Resolve_To procedure Clear (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (others => True)); -- Clear the attached textures for which the mask is True using -- the default values set with Set_Default_Values -- -- For clearing to be effective, the following conditions must apply: -- -- - Write mask off -- - Rasterizer discard disabled -- - Scissor test off or scissor rectangle set to the desired region -- - Called procedure Set_Draw_Buffers with a list of attachments -- -- If a combined depth/stencil texture has been attached, the depth -- and stencil components can be cleared separately, but it may be -- faster to clear both components. procedure Invalidate (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits); -- Invalidate the attached textures for which the mask is True procedure Resolve_To (Object, Subject : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False)) with Pre => Object /= Subject and (Mask.Color or Mask.Depth or Mask.Stencil) and (if Object.Samples > 0 and Subject.Samples > 0 then Object.Samples = Subject.Samples); -- Copy one or more buffers, resolving multiple samples and scaling -- if necessary, from the source to the destination framebuffer -- -- If a buffer is specified in the mask, then the buffer should exist -- in both framebuffers, otherwise the buffer is not copied. Call -- Set_Read_Buffer and Set_Draw_Buffers to control which buffer is read -- from and which buffers are written to. -- -- Format of color buffers may differ and will be converted (if -- supported). Formats of depth and stencil buffers must match. -- -- Note: simultaneously resolving multiple samples and scaling -- requires GL_EXT_framebuffer_multisample_blit_scaled. procedure Attach (Object : in out Framebuffer; Attachment : FB.Attachment_Point; Texture : Textures.Texture; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and (if Attachment in Color_Attachment_Point then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => Object.Has_Attachment (Attachment); -- Attach the texture to the attachment point -- -- The internal format of the texture must be valid for the given -- attachment point. procedure Attach (Object : in out Framebuffer; Texture : Textures.Texture; Level : Textures.Mipmap_Level := 0); -- Attach the texture to an attachment point based on the internal -- format of the texture -- -- Internally calls the procedure Attach above. -- -- If the texture is color renderable, it will always be attached to -- Color_Attachment_0. If you need to attach a texture to a different -- color attachment point then use the other procedure Attach directly. -- -- If the texture is layered and you want to attach a specific layer, -- then you must call the procedure Attach_Layer below instead. procedure Attach_Layer (Object : in out Framebuffer; Attachment : FB.Attachment_Point; Texture : Textures.Texture; Layer : Natural; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and Texture.Layered and (if Attachment in Color_Attachment_Point then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach layer of " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => Object.Has_Attachment (Attachment); -- Attach the selected 1D/2D layer of the texture to the attachment point -- -- The internal format of the texture must be valid for the given -- attachment point. -- -- The texture must be layered (3D, 1D/2D array, cube -- map [array], or 2D multisampled array). procedure Detach (Object : in out Framebuffer; Attachment : FB.Attachment_Point) with Pre => not Object.Default, Post => not Object.Has_Attachment (Attachment); -- Detach any texture currently attached to the given attachment point function Has_Attachment (Object : Framebuffer; Attachment : FB.Attachment_Point) return Boolean; Framebuffer_Incomplete_Error : exception; private package Attachment_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => Textures.Texture, "=" => Textures."="); package Color_Buffer_List_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => GL.Buffers.Color_Buffer_List, "=" => GL.Buffers."="); type Attachment_Array is array (FB.Attachment_Point) of Attachment_Holder.Holder; type Framebuffer (Default : Boolean; Width, Height, Samples : Size) is tagged record GL_Framebuffer : FB.Framebuffer; Attachments : Attachment_Array; Defaults : Buffer_Values; Draw_Buffers : Color_Buffer_List_Holder.Holder; end record; end Orka.Rendering.Framebuffers;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Ada.Containers.Indefinite_Holders; with GL.Buffers; with GL.Objects.Framebuffers; with GL.Objects.Textures; with GL.Types.Colors; with Orka.Contexts; with Orka.Rendering.Buffers; with Orka.Rendering.Textures; with Orka.Windows; package Orka.Rendering.Framebuffers is pragma Preelaborate; use GL.Types; package FB renames GL.Objects.Framebuffers; package Textures renames GL.Objects.Textures; subtype Color_Attachment_Point is FB.Attachment_Point range FB.Color_Attachment_0 .. FB.Color_Attachment_15; type Use_Point_Array is array (Rendering.Framebuffers.Color_Attachment_Point) of Boolean; -- TODO Use as formal parameter in procedure Invalidate type Buffer_Values is record Color : Colors.Color := (0.0, 0.0, 0.0, 0.0); Depth : GL.Buffers.Depth := 1.0; Stencil : GL.Buffers.Stencil_Index := 0; end record; type Framebuffer (Default : Boolean; Width, Height, Samples : Size) is tagged private with Type_Invariant => (if Framebuffer.Default then Framebuffer.Samples = 0); type Framebuffer_Ptr is not null access Framebuffer; function Create_Framebuffer (Width, Height, Samples : Size; Context : Contexts.Context'Class) return Framebuffer with Pre => (if Samples > 0 then Context.Enabled (Contexts.Multisample)), Post => not Create_Framebuffer'Result.Default; function Create_Framebuffer (Width, Height : Size) return Framebuffer with Post => not Create_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function Get_Default_Framebuffer (Window : Orka.Windows.Window'Class) return Framebuffer with Post => Get_Default_Framebuffer'Result.Default; function Create_Default_Framebuffer (Width, Height : Size) return Framebuffer with Post => Create_Default_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function GL_Framebuffer (Object : Framebuffer) return FB.Framebuffer with Inline; ----------------------------------------------------------------------------- function Image (Object : Framebuffer) return String; -- Return a description of the given framebuffer procedure Use_Framebuffer (Object : Framebuffer); -- Use the framebuffer during rendering -- -- The viewport is adjusted to the size of the framebuffer. procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values); -- Set the default values for the color buffers and depth and stencil -- buffers function Default_Values (Object : Framebuffer) return Buffer_Values; -- Return the current default values used when clearing the attached -- textures procedure Set_Read_Buffer (Object : Framebuffer; Buffer : GL.Buffers.Color_Buffer_Selector); -- Set the buffer to use when blitting to another framebuffer with -- procedure Resolve_To procedure Set_Draw_Buffers (Object : in out Framebuffer; Buffers : GL.Buffers.Color_Buffer_List); -- Set the buffers to use when drawing to output variables in a fragment -- shader, when calling procedure Clear, or when another framebuffer -- blits its read buffer to this framebuffer with procedure Resolve_To procedure Clear (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (others => True)); -- Clear the attached textures for which the mask is True using -- the default values set with Set_Default_Values -- -- For clearing to be effective, the following conditions must apply: -- -- - Write mask off -- - Rasterizer discard disabled -- - Scissor test off or scissor rectangle set to the desired region -- - Called procedure Set_Draw_Buffers with a list of attachments -- -- If a combined depth/stencil texture has been attached, the depth -- and stencil components can be cleared separately, but it may be -- faster to clear both components. procedure Invalidate (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits); -- Invalidate the attached textures for which the mask is True procedure Resolve_To (Object, Subject : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False)) with Pre => Object /= Subject and (Mask.Color or Mask.Depth or Mask.Stencil) and (if Object.Samples > 0 and Subject.Samples > 0 then Object.Samples = Subject.Samples); -- Copy one or more buffers, resolving multiple samples and scaling -- if necessary, from the source to the destination framebuffer -- -- If a buffer is specified in the mask, then the buffer should exist -- in both framebuffers, otherwise the buffer is not copied. Call -- Set_Read_Buffer and Set_Draw_Buffers to control which buffer is read -- from and which buffers are written to. -- -- Format of color buffers may differ and will be converted (if -- supported). Formats of depth and stencil buffers must match. -- -- Note: simultaneously resolving multiple samples and scaling -- requires GL_EXT_framebuffer_multisample_blit_scaled. procedure Attach (Object : in out Framebuffer; Attachment : FB.Attachment_Point; Texture : Textures.Texture; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and (if Attachment in Color_Attachment_Point then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => Object.Has_Attachment (Attachment); -- Attach the texture to the attachment point -- -- The internal format of the texture must be valid for the given -- attachment point. procedure Attach (Object : in out Framebuffer; Texture : Textures.Texture; Level : Textures.Mipmap_Level := 0); -- Attach the texture to an attachment point based on the internal -- format of the texture -- -- Internally calls the procedure Attach above. -- -- If the texture is color renderable, it will always be attached to -- Color_Attachment_0. If you need to attach a texture to a different -- color attachment point then use the other procedure Attach directly. -- -- If the texture is layered and you want to attach a specific layer, -- then you must call the procedure Attach_Layer below instead. procedure Attach_Layer (Object : in out Framebuffer; Attachment : FB.Attachment_Point; Texture : Textures.Texture; Layer : Natural; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and Texture.Layered and (if Attachment in Color_Attachment_Point then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach layer of " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => Object.Has_Attachment (Attachment); -- Attach the selected 1D/2D layer of the texture to the attachment point -- -- The internal format of the texture must be valid for the given -- attachment point. -- -- The texture must be layered (3D, 1D/2D array, cube -- map [array], or 2D multisampled array). procedure Detach (Object : in out Framebuffer; Attachment : FB.Attachment_Point) with Pre => not Object.Default, Post => not Object.Has_Attachment (Attachment); -- Detach any texture currently attached to the given attachment point function Has_Attachment (Object : Framebuffer; Attachment : FB.Attachment_Point) return Boolean; Framebuffer_Incomplete_Error : exception; private package Attachment_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => Textures.Texture, "=" => Textures."="); package Color_Buffer_List_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => GL.Buffers.Color_Buffer_List, "=" => GL.Buffers."="); type Attachment_Array is array (FB.Attachment_Point) of Attachment_Holder.Holder; type Framebuffer (Default : Boolean; Width, Height, Samples : Size) is tagged record GL_Framebuffer : FB.Framebuffer; Attachments : Attachment_Array; Defaults : Buffer_Values; Draw_Buffers : Color_Buffer_List_Holder.Holder; end record; end Orka.Rendering.Framebuffers;
Fix aspect Pre of function Create_Framebuffer to allow Samples = 0
orka: Fix aspect Pre of function Create_Framebuffer to allow Samples = 0 Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
1f88169d101b3e8183466f9977f68f1af005edc0
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, 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.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use AWS.SMTP; 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 Recipients_Access) 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 List : Recipients_Access := Message.To (Kind); begin if List = null then List := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. List'Last + 1); begin List (List'Range) := List.all; Free (List); List := To; end; end if; List (List'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); Message.To (Kind) := List; 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 (To_String (Content))); else declare Parts : AWS.Attachments.Alternatives; begin AWS.Attachments.Add (Parts, AWS.Attachments.Value (To_String (Content), Content_Type => Content_Type)); AWS.Attachments.Add (Parts, AWS.Attachments.Value (To_String (Alternative), Content_Type => "text/plain; charset='UTF-8'")); AWS.Attachments.Add (Message.Attachments, Parts); end; 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 => To_String (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 Recipients_Access) return String is Result : Unbounded_String; begin if Recipients /= null then for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; end if; 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 (for all Recipient of Message.To => Recipient = 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 (Clients.TO))); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => (if Message.To (Clients.TO) /= null then Message.To (Clients.TO).all else No_Recipient), CC => (if Message.To (Clients.CC) /= null then Message.To (Clients.CC).all else No_Recipient), BCC => (if Message.To (Clients.BCC) /= null then Message.To (Clients.BCC).all else No_Recipient), 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 (Clients.TO))); 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 (AWA.Mail.Clients.TO)); Free (Message.To (AWA.Mail.Clients.CC)); Free (Message.To (AWA.Mail.Clients.BCC)); 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.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use AWS.SMTP; 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 Recipients_Access) 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 List : Recipients_Access := Message.To (Kind); begin if List = null then List := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. List'Last + 1); begin List (List'Range) := List.all; Free (List); List := To; end; end if; List (List'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); Message.To (Kind) := List; 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 (To_String (Content))); else declare Parts : AWS.Attachments.Alternatives; begin AWS.Attachments.Add (Parts, AWS.Attachments.Value (To_String (Content), Content_Type => Content_Type)); AWS.Attachments.Add (Parts, AWS.Attachments.Value (To_String (Alternative), Content_Type => "text/plain; charset='UTF-8'")); AWS.Attachments.Add (Message.Attachments, Parts); end; 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 => To_String (Content), Content_Id => Content_Id, Content_Type => Content_Type); begin AWS.Attachments.Add (Attachments => Message.Attachments, Name => Content_Id, Data => Data); end Add_Attachment; overriding procedure Add_File_Attachment (Message : in out AWS_Mail_Message; Filename : in String; Content_Id : in String; Content_Type : in String) is Data : constant AWS.Attachments.Content := AWS.Attachments.File (Filename => Filename, Encode => AWS.Attachments.Base64, Content_Id => Content_Id, Content_Type => Content_Type); begin AWS.Attachments.Add (Attachments => Message.Attachments, Name => Content_Id, Data => Data); end Add_File_Attachment; -- ------------------------------ -- Get a printable representation of the email recipients. -- ------------------------------ function Image (Recipients : in Recipients_Access) return String is Result : Unbounded_String; begin if Recipients /= null then for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; end if; return To_String (Result); end Image; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is function Get_To return AWS.SMTP.Recipients is (if Message.To (Clients.TO) /= null then Message.To (Clients.TO).all else No_Recipient); function Get_Cc return AWS.SMTP.Recipients is (if Message.To (Clients.CC) /= null then Message.To (Clients.CC).all else No_Recipient); function Get_Bcc return AWS.SMTP.Recipients is (if Message.To (Clients.BCC) /= null then Message.To (Clients.BCC).all else No_Recipient); Result : AWS.SMTP.Status; begin if (for all Recipient of Message.To => Recipient = 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 (Clients.TO))); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Get_To, CC => Get_Cc, BCC => Get_Bcc, 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 (Clients.TO))); 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 (AWA.Mail.Clients.TO)); Free (Message.To (AWA.Mail.Clients.CC)); Free (Message.To (AWA.Mail.Clients.BCC)); 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_File_Attachment to attach a file to a mail
Implement Add_File_Attachment to attach a file to a mail
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a26c8182ce15341b8b5f9aae28e38c4607c25899
src/security-auth-openid.ads
src/security-auth-openid.ads
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == OpenID == -- The <b>Security.OpenID</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement: -- -- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * <b>Verify</b>: to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- === Initialization === -- The initialization process must be done before each two steps (discovery and verify). -- The OpenID manager must be declared and configured. -- -- Mgr : Security.OpenID.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the OpenID realm and set the OpenID return callback URL. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify"); -- -- After this initialization, the OpenID manager can be used in the authentication process. -- -- === Discovery: creating the authentication URL === -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenID manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an -- URL, below is an example for Google OpenID: -- -- Provider : constant String := "https://www.google.com/accounts/o8/id"; -- OP : Security.OpenID.End_Point; -- Assoc : constant Security.OpenID.Association_Access := new Security.OpenID.Association; -- -- The following steps are performed: -- -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- === Verify: acknowledge the authentication in the callback URL === -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : OpenID.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Mgr.Verify (Assoc.all, Params, Auth); -- if Security.OpenID.Get_Status (Auth) = Security.OpenID.AUTHENTICATED then ... -- Success. -- -- === Principal creation === -- After the user is successfully authenticated, a user principal can be created and saved in -- the session. The user principal can then be used to assign permissions to that user and -- enforce the application permissions using the security policy manger. -- -- P : Security.OpenID.Principal_Access := Security.OpenID.Create_Principal (Auth); -- private package Security.Auth.OpenID is -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is new Security.Auth.Manager with private; -- Initialize the authentication realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- 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. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private type Manager is new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; end record; end Security.Auth.OpenID;
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- === OpenID Configuration == -- The Open ID provider needs the following configuration parameters: -- -- openid.realm The OpenID realm parameter passed in the authentication URL. -- openid.callback_url The OpenID return_to parameter. -- private package Security.Auth.OpenID is -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is new Security.Auth.Manager with private; -- Initialize the OpenID authentication realm. Get the <tt>openid.realm</tt> -- and <tt>openid.callback_url</tt> parameters to configure the realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- 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. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private type Manager is new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; end record; end Security.Auth.OpenID;
Document the OpenID configuration parameters
Document the OpenID configuration parameters
Ada
apache-2.0
stcarrez/ada-security
cb0311e6836669b5a54bc450fed6954508fcb56c
src/security-policies.ads
src/security-policies.ads
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- 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; pragma Inline_Always (Get_Controller); -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
Remove the Get_Controller function
Remove the Get_Controller function
Ada
apache-2.0
stcarrez/ada-security
c94483ecfbd6d6bf809d4e98964be15199d26c5a
src/util-properties-json.adb
src/util-properties-json.adb
----------------------------------------------------------------------- -- util-properties-json -- read json files into properties -- Copyright (C) 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.IO.JSON; with Util.Stacks; with Util.Log; with Util.Beans.Objects; package body Util.Properties.JSON is type Natural_Access is access all Natural; package Length_Stack is new Util.Stacks (Element_Type => Natural, Element_Type_Access => Natural_Access); type Parser is abstract limited new Util.Serialize.IO.Reader with record Base_Name : Ada.Strings.Unbounded.Unbounded_String; Lengths : Length_Stack.Stack; Separator : Ada.Strings.Unbounded.Unbounded_String; Separator_Length : Natural; end record; -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. overriding procedure Start_Object (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. overriding procedure Finish_Object (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class); overriding procedure Start_Array (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class); overriding procedure Finish_Array (Handler : in out Parser; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class); -- ----------------------- -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ----------------------- overriding procedure Start_Object (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class) is begin if Name'Length > 0 then Ada.Strings.Unbounded.Append (Handler.Base_Name, Name); Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator); Length_Stack.Push (Handler.Lengths); Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length; end if; end Start_Object; -- ----------------------- -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ----------------------- overriding procedure Finish_Object (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class) is Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name); begin if Name'Length > 0 then Ada.Strings.Unbounded.Delete (Handler.Base_Name, Len - Name'Length - Handler.Separator_Length + 1, Len); end if; end Finish_Object; overriding procedure Start_Array (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class) is begin Handler.Start_Object (Name, Logger); -- Util.Serialize.IO.JSON.Parser (Handler).Start_Array (Name); end Start_Array; overriding procedure Finish_Array (Handler : in out Parser; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class) is begin Parser'Class (Handler).Set_Member ("length", Util.Beans.Objects.To_Object (Count), Logger); Handler.Finish_Object (Name, Logger); -- Util.Serialize.IO.JSON.Parser (Handler).Finish_Array (Name, Count); end Finish_Array; -- ----------------------- -- Parse the JSON content and put the flattened content in the property manager. -- ----------------------- procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class; Content : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with record Manager : access Util.Properties.Manager'Class; end record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); begin Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; R : Util.Serialize.IO.JSON.Parser; begin P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; P.Manager := Manager'Access; R.Parse_String (Content, P); if R.Has_Error then raise Util.Serialize.IO.Parse_Error; end if; end Parse_JSON; -- ----------------------- -- Read the JSON file into the property manager. -- The JSON content is flatten into Flatten the JSON content and add the properties. -- ----------------------- procedure Read_JSON (Manager : in out Util.Properties.Manager'Class; Path : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with record Manager : access Util.Properties.Manager'Class; end record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); begin Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; R : Util.Serialize.IO.JSON.Parser; begin P.Manager := Manager'Access; P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; R.Parse (Path, P); if R.Has_Error then raise Util.Serialize.IO.Parse_Error; end if; end Read_JSON; end Util.Properties.JSON;
----------------------------------------------------------------------- -- util-properties-json -- read json files into properties -- Copyright (C) 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.IO.JSON; with Util.Stacks; with Util.Log; with Util.Beans.Objects; package body Util.Properties.JSON is type Natural_Access is access all Natural; package Length_Stack is new Util.Stacks (Element_Type => Natural, Element_Type_Access => Natural_Access); type Parser is abstract limited new Util.Serialize.IO.Reader with record Base_Name : Ada.Strings.Unbounded.Unbounded_String; Lengths : Length_Stack.Stack; Separator : Ada.Strings.Unbounded.Unbounded_String; Separator_Length : Natural; end record; -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. overriding procedure Start_Object (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. overriding procedure Finish_Object (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class); overriding procedure Start_Array (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class); overriding procedure Finish_Array (Handler : in out Parser; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class); -- ----------------------- -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ----------------------- overriding procedure Start_Object (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Logger); begin if Name'Length > 0 then Ada.Strings.Unbounded.Append (Handler.Base_Name, Name); Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator); Length_Stack.Push (Handler.Lengths); Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length; end if; end Start_Object; -- ----------------------- -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ----------------------- overriding procedure Finish_Object (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Logger); Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name); begin if Name'Length > 0 then Ada.Strings.Unbounded.Delete (Handler.Base_Name, Len - Name'Length - Handler.Separator_Length + 1, Len); end if; end Finish_Object; overriding procedure Start_Array (Handler : in out Parser; Name : in String; Logger : in out Util.Log.Logging'Class) is begin Handler.Start_Object (Name, Logger); -- Util.Serialize.IO.JSON.Parser (Handler).Start_Array (Name); end Start_Array; overriding procedure Finish_Array (Handler : in out Parser; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class) is begin Parser'Class (Handler).Set_Member ("length", Util.Beans.Objects.To_Object (Count), Logger); Handler.Finish_Object (Name, Logger); -- Util.Serialize.IO.JSON.Parser (Handler).Finish_Array (Name, Count); end Finish_Array; -- ----------------------- -- Parse the JSON content and put the flattened content in the property manager. -- ----------------------- procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class; Content : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with record Manager : access Util.Properties.Manager'Class; end record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is pragma Unreferenced (Logger, Attribute); begin Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; R : Util.Serialize.IO.JSON.Parser; begin P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; P.Manager := Manager'Access; R.Parse_String (Content, P); if R.Has_Error then raise Util.Serialize.IO.Parse_Error; end if; end Parse_JSON; -- ----------------------- -- Read the JSON file into the property manager. -- The JSON content is flatten into Flatten the JSON content and add the properties. -- ----------------------- procedure Read_JSON (Manager : in out Util.Properties.Manager'Class; Path : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with record Manager : access Util.Properties.Manager'Class; end record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is pragma Unreferenced (Logger, Attribute); begin Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; R : Util.Serialize.IO.JSON.Parser; begin P.Manager := Manager'Access; P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; R.Parse (Path, P); if R.Has_Error then raise Util.Serialize.IO.Parse_Error; end if; end Read_JSON; end Util.Properties.JSON;
Fix compilation warning unused Logger parameter
Fix compilation warning unused Logger parameter
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0bd2434755de666c27eebbbb852b91a5b47e6e8b
src/tests/ahven/ahven-xml_runner.adb
src/tests/ahven/ahven-xml_runner.adb
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.IO_Exceptions; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; elsif Str (I) = '"' then Result (Pos) := '''; Pos := Pos + 1; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop : loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop : loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop : loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop : loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); begin loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; -- The End_Error exception is sometimes raised. exception when Ada.IO_Exceptions.End_Error => null; end; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.IO_Exceptions; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; elsif Str (I) = '"' then Result (Pos) := '''; Pos := Pos + 1; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop : loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop : loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop : loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop : loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); begin loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); case Char is when ASCII.NUL => Put (File, "&#0;"); when ASCII.SOH => Put (File, "&#1;"); when ASCII.STX => Put (File, "&#2;"); when ASCII.ETX => Put (File, "&#3;"); when ASCII.EOT => Put (File, "&#4;"); when ASCII.ENQ => Put (File, "&#5;"); when ASCII.ACK => Put (File, "&#6;"); when ASCII.BEL => Put (File, "&#7;"); when ASCII.BS => Put (File, "&#8;"); when ASCII.VT => Put (File, "&#xB;"); when ASCII.FF => Put (File, "&#xC;"); when ASCII.SO => Put (File, "&#xE;"); when ASCII.SI => Put (File, "&#xF;"); when ASCII.DLE => Put (File, "&#x10;"); when ASCII.DC1 => Put (File, "&#x11;"); when ASCII.DC2 => Put (File, "&#x12;"); when ASCII.DC3 => Put (File, "&#x13;"); when ASCII.DC4 => Put (File, "&#x14;"); when ASCII.NAK => Put (File, "&#x15;"); when ASCII.SYN => Put (File, "&#x16;"); when ASCII.ETB => Put (File, "&#x17;"); when ASCII.CAN => Put (File, "&#x18;"); when ASCII.EM => Put (File, "&#x19;"); when ASCII.SUB => Put (File, "&#x1A;"); when ASCII.ESC => Put (File, "&#x1B;"); when ASCII.FS => Put (File, "&#x1C;"); when ASCII.GS => Put (File, "&#x1D;"); when ASCII.RS => Put (File, "&#x1E;"); when ASCII.US => Put (File, "&#x1F;"); when others => Put (File, Char); end case; if End_Of_Line (Handle) then New_Line (File); end if; end loop; -- The End_Error exception is sometimes raised. exception when Ada.IO_Exceptions.End_Error => null; end; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
Fix writing <![CDATA blocks to escape invalid control sequences in range 0x00..0x1F See https://www.w3.org/TR/xml/#charsets
Fix writing <![CDATA blocks to escape invalid control sequences in range 0x00..0x1F See https://www.w3.org/TR/xml/#charsets
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4cdbe1eb4b9b26fc493d4e0c416d2211cf8b634a
orka/src/orka/interface/orka-resources-locations.ads
orka/src/orka/interface/orka-resources-locations.ads
-- 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. with Ada.IO_Exceptions; package Orka.Resources.Locations is pragma Preelaborate; type Location is limited interface; function Exists (Object : Location; Path : String) return Boolean is abstract; function Read_Data (Object : Location; Path : String) return Byte_Array_Pointers.Pointer is abstract; -- Return the data of the file at the given path in the location if -- Path identifies an existing file, otherwise the exception Name_Error -- is raised -- -- If the file at the given path could not be read for any reason -- then any kind of error is raised. type Writable_Location is limited interface and Location; procedure Write_Data (Object : Writable_Location; Path : String; Data : Byte_Array) is abstract; -- Write data to a non-existing file at the given path in the location -- -- If the file at the given path could not be created or written to -- for any reason then any kind of error is raised. procedure Append_Data (Object : Writable_Location; Path : String; Data : Byte_Array) is abstract; -- Append data to a (non-)existing file at the given path in the location -- -- If the file at the given path could not be created or written to -- for any reason then any kind of error is raised. type Location_Access is access Location'Class; subtype Location_Ptr is not null Location_Access; type Writable_Location_Ptr is not null access Writable_Location'Class; Name_Error : exception renames Ada.IO_Exceptions.Name_Error; Path_Separator : constant Character with Import, Convention => C, External_Name => "__gnat_dir_separator"; end Orka.Resources.Locations;
-- 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. with Ada.IO_Exceptions; package Orka.Resources.Locations is pragma Preelaborate; type Location is limited interface; function Exists (Object : Location; Path : String) return Boolean is abstract; function Read_Data (Object : Location; Path : String) return Byte_Array_Pointers.Pointer is abstract; -- Return the data of the file at the given path in the location if -- Path identifies an existing file, otherwise the exception Name_Error -- is raised -- -- If the file at the given path could not be read for any reason -- then any kind of error is raised. type Writable_Location is limited interface and Location; procedure Write_Data (Object : Writable_Location; Path : String; Data : Byte_Array) is abstract; -- Write data to a non-existing file at the given path in the location -- -- If the file at the given path could not be created or written to -- for any reason then any kind of error is raised. procedure Append_Data (Object : Writable_Location; Path : String; Data : Byte_Array) is abstract; -- Append data to a (non-)existing file at the given path in the location -- -- If the file at the given path could not be created or written to -- for any reason then any kind of error is raised. type Location_Access is access all Location'Class; subtype Location_Ptr is not null Location_Access; type Writable_Location_Ptr is not null access Writable_Location'Class; Name_Error : exception renames Ada.IO_Exceptions.Name_Error; Path_Separator : constant Character with Import, Convention => C, External_Name => "__gnat_dir_separator"; end Orka.Resources.Locations;
Make Location_Access a general access type
orka: Make Location_Access a general access type This is apparently needed to convert a Writable_Location_Ptr to a Location_Ptr. Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
728f5750fd2b30ac392befbcd05510b82e64540c
awa/plugins/awa-storages/src/awa-storages-beans.adb
awa/plugins/awa-storages/src/awa-storages-beans.adb
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 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.Containers; with Util.Log.Loggers; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with AWA.Permissions; with AWA.Helpers.Requests; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is use Ada.Strings.Unbounded; package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Beans"); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is use type ADO.Identifier; Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; Id : ADO.Identifier; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then Id := ADO.Utils.To_Identifier (Value); if Id /= ADO.NO_IDENTIFIER then Manager.Load_Storage (From, Id); end if; elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); if Part.Get_Size > 100_000 then Manager.Save (Bean, Part, AWA.Storages.Models.FILE); else Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end if; exception when AWA.Permissions.NO_PERMISSION => Bean.Error := True; Log.Error ("Saving document is refused by the permission controller"); raise; when E : others => Bean.Error := True; Log.Error ("Exception when saving the document", E); raise; end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Outcome := To_Unbounded_String (if Bean.Error then "failure" else "success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (1).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Util.Log.Loggers; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with AWA.Permissions; with AWA.Helpers.Requests; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is use Ada.Strings.Unbounded; package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Beans"); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is use type ADO.Identifier; Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; Id : ADO.Identifier; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then Id := ADO.Utils.To_Identifier (Value); if Id /= ADO.NO_IDENTIFIER then Manager.Load_Storage (From, Id); end if; elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); if Part.Get_Size > 100_000 then Manager.Save (Bean, Part, AWA.Storages.Models.FILE); else Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end if; exception when AWA.Permissions.NO_PERMISSION => Bean.Error := True; Log.Error ("Saving document is refused by the permission controller"); raise; when E : others => Bean.Error := True; Log.Error ("Exception when saving the document", E); raise; end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Outcome := To_Unbounded_String (if Bean.Error then "failure" else "success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (1).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; overriding procedure Load (Into : in out Storage_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the image information. Query.Set_Query (AWA.Storages.Models.Query_Storage_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); Into.Load (Session, Query); exception when ADO.Objects.NOT_FOUND => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; -- ------------------------------ -- Create the Storage_Bean bean instance. -- ------------------------------ function Create_Storage_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_Bean_Access := new Storage_Bean; begin Object.Module := Module; Object.Id := ADO.NO_IDENTIFIER; return Object.all'Access; end Create_Storage_Bean; end AWA.Storages.Beans;
Implement Load and Create_Storage_Bean operations
Implement Load and Create_Storage_Bean operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
25bc5889fadb8de401b7f26110be229a8f67d42a
src/security-oauth.ads
src/security-oauth.ads
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 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; -- == OAuth == -- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization -- framework as defined by the IETF working group. -- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26 package Security.OAuth is -- OAuth 2.0: Section 10.2.2. Initial Registry Contents -- RFC 6749: 11.2.2. Initial Registry Contents CLIENT_ID : constant String := "client_id"; CLIENT_SECRET : constant String := "client_secret"; RESPONSE_TYPE : constant String := "response_type"; REDIRECT_URI : constant String := "redirect_uri"; SCOPE : constant String := "scope"; STATE : constant String := "state"; CODE : constant String := "code"; ERROR_DESCRIPTION : constant String := "error_description"; ERROR_URI : constant String := "error_uri"; GRANT_TYPE : constant String := "grant_type"; ACCESS_TOKEN : constant String := "access_token"; TOKEN_TYPE : constant String := "token_type"; EXPIRES_IN : constant String := "expires_in"; USERNAME : constant String := "username"; PASSWORD : constant String := "password"; REFRESH_TOKEN : constant String := "refresh_token"; -- RFC 6749: 5.2. Error Response INVALID_REQUEST : aliased constant String := "invalid_request"; INVALID_CLIENT : aliased constant String := "invalid_client"; INVALID_GRANT : aliased constant String := "invalid_grant"; UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client"; UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type"; INVALID_SCOPE : aliased constant String := "invalid_scope"; -- RFC 6749: 4.1.2.1. Error Response ACCESS_DENIED : aliased constant String := "access_denied"; UNSUPPORTED_RESPONSE_TYPE : aliased constant String := "unsupported_response_type"; SERVER_ERROR : aliased constant String := "server_error"; TEMPORARILY_UNAVAILABLE : aliased constant String := "temporarily_unavailable"; type Client_Authentication_Type is (AUTH_NONE, AUTH_BASIC); -- ------------------------------ -- 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; -- Get the application identifier. function Get_Application_Identifier (App : in Application) return String; -- 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 client authentication method used when doing OAuth calls for this application. -- See RFC 6749, 2.3. Client Authentication procedure Set_Client_Authentication (App : in out Application; Method : in Client_Authentication_Type); private type Application is tagged record Client_Id : Ada.Strings.Unbounded.Unbounded_String; Secret : Ada.Strings.Unbounded.Unbounded_String; Callback : Ada.Strings.Unbounded.Unbounded_String; Client_Auth : Client_Authentication_Type := AUTH_NONE; end record; end Security.OAuth;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 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; -- = OAuth = -- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization -- framework as defined by the IETF working group. -- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26 -- -- @include security-oauth-clients.ads -- @include security-oauth-servers.ads package Security.OAuth is -- OAuth 2.0: Section 10.2.2. Initial Registry Contents -- RFC 6749: 11.2.2. Initial Registry Contents CLIENT_ID : constant String := "client_id"; CLIENT_SECRET : constant String := "client_secret"; RESPONSE_TYPE : constant String := "response_type"; REDIRECT_URI : constant String := "redirect_uri"; SCOPE : constant String := "scope"; STATE : constant String := "state"; CODE : constant String := "code"; ERROR_DESCRIPTION : constant String := "error_description"; ERROR_URI : constant String := "error_uri"; GRANT_TYPE : constant String := "grant_type"; ACCESS_TOKEN : constant String := "access_token"; TOKEN_TYPE : constant String := "token_type"; EXPIRES_IN : constant String := "expires_in"; USERNAME : constant String := "username"; PASSWORD : constant String := "password"; REFRESH_TOKEN : constant String := "refresh_token"; -- RFC 6749: 5.2. Error Response INVALID_REQUEST : aliased constant String := "invalid_request"; INVALID_CLIENT : aliased constant String := "invalid_client"; INVALID_GRANT : aliased constant String := "invalid_grant"; UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client"; UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type"; INVALID_SCOPE : aliased constant String := "invalid_scope"; -- RFC 6749: 4.1.2.1. Error Response ACCESS_DENIED : aliased constant String := "access_denied"; UNSUPPORTED_RESPONSE_TYPE : aliased constant String := "unsupported_response_type"; SERVER_ERROR : aliased constant String := "server_error"; TEMPORARILY_UNAVAILABLE : aliased constant String := "temporarily_unavailable"; type Client_Authentication_Type is (AUTH_NONE, AUTH_BASIC); -- ------------------------------ -- 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; -- Get the application identifier. function Get_Application_Identifier (App : in Application) return String; -- 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 client authentication method used when doing OAuth calls for this application. -- See RFC 6749, 2.3. Client Authentication procedure Set_Client_Authentication (App : in out Application; Method : in Client_Authentication_Type); private type Application is tagged record Client_Id : Ada.Strings.Unbounded.Unbounded_String; Secret : Ada.Strings.Unbounded.Unbounded_String; Callback : Ada.Strings.Unbounded.Unbounded_String; Client_Auth : Client_Authentication_Type := AUTH_NONE; end record; end Security.OAuth;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-security
2aa01b902b87176808a14d43b207f2b3bec812b5
awa/plugins/awa-mail/src/awa-mail-components-factory.adb
awa/plugins/awa-mail/src/awa-mail-components-factory.adb
----------------------------------------------------------------------- -- awa-mail-components-factory -- Mail UI Component Factory -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Views.Nodes; with ASF.Components.Base; with AWA.Mail.Modules; with AWA.Mail.Components.Messages; with AWA.Mail.Components.Recipients; package body AWA.Mail.Components.Factory is use ASF.Components.Base; use ASF.Views.Nodes; function Create_Bcc return UIComponent_Access; function Create_Body return UIComponent_Access; function Create_Cc return UIComponent_Access; function Create_From return UIComponent_Access; function Create_Message return UIComponent_Access; function Create_To return UIComponent_Access; function Create_Subject return UIComponent_Access; URI : aliased constant String := "http://code.google.com/p/ada-awa/mail"; BCC_TAG : aliased constant String := "bcc"; BODY_TAG : aliased constant String := "body"; CC_TAG : aliased constant String := "cc"; FROM_TAG : aliased constant String := "from"; MESSAGE_TAG : aliased constant String := "message"; SUBJECT_TAG : aliased constant String := "subject"; TO_TAG : aliased constant String := "to"; -- ------------------------------ -- Create an UIMailRecipient component -- ------------------------------ function Create_Bcc return UIComponent_Access is Result : constant Recipients.UIMailRecipient_Access := new Recipients.UIMailRecipient; begin Result.Set_Recipient (AWA.Mail.Clients.BCC); return Result.all'Access; end Create_Bcc; -- ------------------------------ -- Create an UIMailBody component -- ------------------------------ function Create_Body return UIComponent_Access is begin return new Messages.UIMailBody; end Create_Body; -- ------------------------------ -- Create an UIMailRecipient component -- ------------------------------ function Create_Cc return UIComponent_Access is Result : constant Recipients.UIMailRecipient_Access := new Recipients.UIMailRecipient; begin Result.Set_Recipient (AWA.Mail.Clients.CC); return Result.all'Access; end Create_Cc; -- ------------------------------ -- Create an UISender component -- ------------------------------ function Create_From return UIComponent_Access is begin return new Recipients.UISender; end Create_From; -- ------------------------------ -- Create an UIMailMessage component -- ------------------------------ function Create_Message return UIComponent_Access is use type AWA.Mail.Modules.Mail_Module_Access; Result : constant Messages.UIMailMessage_Access := new Messages.UIMailMessage; Module : constant AWA.Mail.Modules.Mail_Module_Access := AWA.Mail.Modules.Get_Mail_Module; begin if Module = null then return null; end if; Result.Set_Message (Module.Create_Message); return Result.all'Access; end Create_Message; -- ------------------------------ -- Create an UIMailSubject component -- ------------------------------ function Create_Subject return UIComponent_Access is begin return new Messages.UIMailSubject; end Create_Subject; -- ------------------------------ -- Create an UIMailRecipient component -- ------------------------------ function Create_To return UIComponent_Access is begin return new Recipients.UIMailRecipient; end Create_To; Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => BCC_TAG'Access, Component => Create_Bcc'Access, Tag => Create_Component_Node'Access), 2 => (Name => BODY_TAG'Access, Component => Create_Body'Access, Tag => Create_Component_Node'Access), 3 => (Name => CC_TAG'Access, Component => Create_Cc'Access, Tag => Create_Component_Node'Access), 4 => (Name => FROM_TAG'Access, Component => Create_From'Access, Tag => Create_Component_Node'Access), 5 => (Name => MESSAGE_TAG'Access, Component => Create_Message'Access, Tag => Create_Component_Node'Access), 6 => (Name => SUBJECT_TAG'Access, Component => Create_Subject'Access, Tag => Create_Component_Node'Access), 7 => (Name => TO_TAG'Access, Component => Create_To'Access, Tag => Create_Component_Node'Access) ); Mail_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Bindings'Access); -- ------------------------------ -- Get the AWA Mail component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Mail_Factory'Access; end Definition; end AWA.Mail.Components.Factory;
----------------------------------------------------------------------- -- awa-mail-components-factory -- Mail UI Component Factory -- 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 ASF.Views.Nodes; with ASF.Components.Base; with AWA.Mail.Modules; with AWA.Mail.Components.Messages; with AWA.Mail.Components.Recipients; with AWA.Mail.Components.Attachments; package body AWA.Mail.Components.Factory is use ASF.Components.Base; use ASF.Views.Nodes; function Create_Bcc return UIComponent_Access; function Create_Body return UIComponent_Access; function Create_Cc return UIComponent_Access; function Create_From return UIComponent_Access; function Create_Message return UIComponent_Access; function Create_To return UIComponent_Access; function Create_Subject return UIComponent_Access; function Create_Attachment return UIComponent_Access; URI : aliased constant String := "http://code.google.com/p/ada-awa/mail"; BCC_TAG : aliased constant String := "bcc"; BODY_TAG : aliased constant String := "body"; CC_TAG : aliased constant String := "cc"; FROM_TAG : aliased constant String := "from"; MESSAGE_TAG : aliased constant String := "message"; SUBJECT_TAG : aliased constant String := "subject"; TO_TAG : aliased constant String := "to"; ATTACHMENT_TAG : aliased constant String := "attachment"; -- ------------------------------ -- Create an UIMailRecipient component -- ------------------------------ function Create_Bcc return UIComponent_Access is Result : constant Recipients.UIMailRecipient_Access := new Recipients.UIMailRecipient; begin Result.Set_Recipient (AWA.Mail.Clients.BCC); return Result.all'Access; end Create_Bcc; -- ------------------------------ -- Create an UIMailBody component -- ------------------------------ function Create_Body return UIComponent_Access is begin return new Messages.UIMailBody; end Create_Body; -- ------------------------------ -- Create an UIMailRecipient component -- ------------------------------ function Create_Cc return UIComponent_Access is Result : constant Recipients.UIMailRecipient_Access := new Recipients.UIMailRecipient; begin Result.Set_Recipient (AWA.Mail.Clients.CC); return Result.all'Access; end Create_Cc; -- ------------------------------ -- Create an UISender component -- ------------------------------ function Create_From return UIComponent_Access is begin return new Recipients.UISender; end Create_From; -- ------------------------------ -- Create an UIMailMessage component -- ------------------------------ function Create_Message return UIComponent_Access is use type AWA.Mail.Modules.Mail_Module_Access; Result : constant Messages.UIMailMessage_Access := new Messages.UIMailMessage; Module : constant AWA.Mail.Modules.Mail_Module_Access := AWA.Mail.Modules.Get_Mail_Module; begin if Module = null then return null; end if; Result.Set_Message (Module.Create_Message); return Result.all'Access; end Create_Message; -- ------------------------------ -- Create an UIMailSubject component -- ------------------------------ function Create_Subject return UIComponent_Access is begin return new Messages.UIMailSubject; end Create_Subject; -- ------------------------------ -- Create an UIMailRecipient component -- ------------------------------ function Create_To return UIComponent_Access is begin return new Recipients.UIMailRecipient; end Create_To; -- ------------------------------ -- Create an UIMailAttachment component -- ------------------------------ function Create_Attachment return UIComponent_Access is begin return new Attachments.UIMailAttachment; end Create_Attachment; Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => ATTACHMENT_TAG'Access, Component => Create_Attachment'Access, Tag => Create_Component_Node'Access), 2 => (Name => BCC_TAG'Access, Component => Create_Bcc'Access, Tag => Create_Component_Node'Access), 3 => (Name => BODY_TAG'Access, Component => Create_Body'Access, Tag => Create_Component_Node'Access), 4 => (Name => CC_TAG'Access, Component => Create_Cc'Access, Tag => Create_Component_Node'Access), 5 => (Name => FROM_TAG'Access, Component => Create_From'Access, Tag => Create_Component_Node'Access), 6 => (Name => MESSAGE_TAG'Access, Component => Create_Message'Access, Tag => Create_Component_Node'Access), 7 => (Name => SUBJECT_TAG'Access, Component => Create_Subject'Access, Tag => Create_Component_Node'Access), 8 => (Name => TO_TAG'Access, Component => Create_To'Access, Tag => Create_Component_Node'Access) ); Mail_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Bindings'Access); -- ------------------------------ -- Get the AWA Mail component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Mail_Factory'Access; end Definition; end AWA.Mail.Components.Factory;
Update the factory to add the <mail:attachment>
Update the factory to add the <mail:attachment>
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b645e2853dbf67b23d8a9421ab6821c4dae1661a
awa/plugins/awa-storages/src/awa-storages-beans.adb
awa/plugins/awa-storages/src/awa-storages-beans.adb
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Helpers.Requests; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" then Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value)); elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Bean); begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (0).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Helpers.Requests; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value)); elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Bean); begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (0).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
Update the upload_bean to setup the storage id only when the value is not empty
Update the upload_bean to setup the storage id only when the value is not empty
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
015b005c41d79b5f8d87457b772785a4e3017b87
awa/plugins/awa-storages/src/awa-storages-beans.ads
awa/plugins/awa-storages/src/awa-storages-beans.ads
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2016, 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 AWA.Storages.Models; with AWA.Storages.Modules; with ASF.Parts; with ADO; with Util.Beans.Objects; with Util.Beans.Basic; -- == Storage Beans == -- The <tt>Upload_Bean</tt> type is used to upload a file in the storage space. -- It expect that the folder already exists. -- -- The <tt>Folder_Bean</tt> type controls the creation of new folders. -- -- The <tt>Storage_List_Bean</tt> type gives the files associated with a given folder. package AWA.Storages.Beans is FOLDER_ID_PARAMETER : constant String := "folderId"; -- ------------------------------ -- Upload Bean -- ------------------------------ -- The <b>Upload_Bean</b> allows to upload a file in the storage space. type Upload_Bean is new AWA.Storages.Models.Upload_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; Folder_Id : ADO.Identifier; Error : Boolean := False; end record; type Upload_Bean_Access is access all Upload_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Save the uploaded file in the storage service. -- @method procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class); -- Upload the file. overriding procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the file. overriding procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Publish the file. overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Upload_Bean bean instance. function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Folder Bean -- ------------------------------ -- The <b>Folder_Bean</b> allows to create or update the folder name. type Folder_Bean is new AWA.Storages.Models.Storage_Folder_Ref and Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; end record; type Folder_Bean_Access is access all Folder_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the folder. procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Init_Flag is (INIT_FOLDER, INIT_FOLDER_LIST, INIT_FILE_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Storage List Bean -- ------------------------------ -- This bean represents a list of storage files for a given folder. type Storage_List_Bean is new AWA.Storages.Models.Storage_List_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; -- Current folder. Folder : aliased Folder_Bean; Folder_Bean : Folder_Bean_Access; -- List of folders. Folder_List : aliased AWA.Storages.Models.Folder_Info_List_Bean; Folder_List_Bean : AWA.Storages.Models.Folder_Info_List_Bean_Access; -- List of files. Files_List : aliased AWA.Storages.Models.Storage_Info_List_Bean; Files_List_Bean : AWA.Storages.Models.Storage_Info_List_Bean_Access; Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Storage_List_Bean_Access is access all Storage_List_Bean'Class; -- Load the folder instance. procedure Load_Folder (Storage : in Storage_List_Bean); -- Load the list of folders. procedure Load_Folders (Storage : in Storage_List_Bean); -- Load the list of files associated with the current folder. procedure Load_Files (Storage : in Storage_List_Bean); overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the files and folder information. overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Folder_List_Bean bean instance. function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Storage_List_Bean bean instance. function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2016, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Storages.Models; with AWA.Storages.Modules; with ASF.Parts; with ADO; with Util.Beans.Objects; with Util.Beans.Basic; -- == Storage Beans == -- The <tt>Upload_Bean</tt> type is used to upload a file in the storage space. -- It expect that the folder already exists. -- -- The <tt>Folder_Bean</tt> type controls the creation of new folders. -- -- The <tt>Storage_List_Bean</tt> type gives the files associated with a given folder. package AWA.Storages.Beans is FOLDER_ID_PARAMETER : constant String := "folderId"; -- ------------------------------ -- Upload Bean -- ------------------------------ -- The <b>Upload_Bean</b> allows to upload a file in the storage space. type Upload_Bean is new AWA.Storages.Models.Upload_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; Folder_Id : ADO.Identifier; Error : Boolean := False; end record; type Upload_Bean_Access is access all Upload_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Save the uploaded file in the storage service. -- @method procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class); -- Upload the file. overriding procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the file. overriding procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Publish the file. overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Upload_Bean bean instance. function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Folder Bean -- ------------------------------ -- The <b>Folder_Bean</b> allows to create or update the folder name. type Folder_Bean is new AWA.Storages.Models.Storage_Folder_Ref and Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; end record; type Folder_Bean_Access is access all Folder_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the folder. procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Init_Flag is (INIT_FOLDER, INIT_FOLDER_LIST, INIT_FILE_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Storage List Bean -- ------------------------------ -- This bean represents a list of storage files for a given folder. type Storage_List_Bean is new AWA.Storages.Models.Storage_List_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; -- Current folder. Folder : aliased Folder_Bean; Folder_Bean : Folder_Bean_Access; -- List of folders. Folder_List : aliased AWA.Storages.Models.Folder_Info_List_Bean; Folder_List_Bean : AWA.Storages.Models.Folder_Info_List_Bean_Access; -- List of files. Files_List : aliased AWA.Storages.Models.Storage_Info_List_Bean; Files_List_Bean : AWA.Storages.Models.Storage_Info_List_Bean_Access; Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Storage_List_Bean_Access is access all Storage_List_Bean'Class; -- Load the folder instance. procedure Load_Folder (Storage : in Storage_List_Bean); -- Load the list of folders. procedure Load_Folders (Storage : in Storage_List_Bean); -- Load the list of files associated with the current folder. procedure Load_Files (Storage : in Storage_List_Bean); overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the files and folder information. overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Folder_List_Bean bean instance. function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Storage_List_Bean bean instance. function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Storage Bean -- ------------------------------ -- Information about a document (excluding the document data itself). type Storage_Bean is new AWA.Storages.Models.Storage_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access; end record; type Storage_Bean_Access is access all Storage_Bean'Class; overriding procedure Load (Into : in out Storage_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Storage_Bean bean instance. function Create_Storage_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Storages.Beans;
Declare the Storage_Bean type with Load and Create_Storage_Bean operations
Declare the Storage_Bean type with Load and Create_Storage_Bean operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9a88256ad240402fc48974bf686062d017e43571
awa/plugins/awa-wikis/regtests/awa-wikis-tests.adb
awa/plugins/awa-wikis/regtests/awa-wikis-tests.adb
----------------------------------------------------------------------- -- awa-wikis-tests -- Unit tests for wikis module -- 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 Util.Test_Caller; with Util.Strings; with Servlet.Streams; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Wikis.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Wikis"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load_List (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save", Test_Create_Wiki'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (missing)", Test_Missing_Page'Access); end Add_Tests; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is function Get_Link (Title : in String) return String; Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; function Get_Link (Title : in String) return String is Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title); end Get_Link; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/wikis/tags/" & Wiki, "wiki-list-tagged.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki tag page is invalid"); if Page'Length > 0 then ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/" & Page, "wiki-page-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "The wiki page content", Reply, "Wiki page " & Page & " is invalid"); declare Info : constant String := Get_Link ("Info"); History : constant String := Get_Link ("History"); begin Util.Tests.Assert_Matches (T, "/asfunit/wikis/info/[0-9]+/[0-9]+$", Info, "Invalid wiki info link in the response"); Util.Tests.Assert_Matches (T, "/asfunit/wikis/history/[0-9]+/[0-9]+$", History, "Invalid wiki history link in the response"); -- Get the information page. ASF.Tests.Do_Get (Request, Reply, Info (Info'First + 8 .. Info'Last), "wiki-info-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-word-list", Reply, "Wiki info page " & Page & " is invalid"); -- Get the history page. ASF.Tests.Do_Get (Request, Reply, History (History'First + 8 .. History'Last), "wiki-history-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-page-version", Reply, "Wiki history page " & Page & " is invalid"); end; end if; end Verify_Anonymous; -- ------------------------------ -- Verify that the wiki lists contain the given page. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Page : in String) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list recent page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/popular", "wiki-list-popular.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list popular page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list popular page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name", "wiki-list-name.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name/grid", "wiki-list-name-grid.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name/grid page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name/grid page does not reference the page"); end Verify_List_Contains; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Wiki (T : in out Test) is procedure Create_Page (Name : in String; Title : in String); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; procedure Create_Page (Name : in String; Title : in String) is begin Request.Set_Parameter ("page-wiki-id", To_String (T.Wiki_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("page-title", Title); Request.Set_Parameter ("text", "# Main title" & ASCII.LF & "* The wiki page content." & ASCII.LF & "* Second item." & ASCII.LF); Request.Set_Parameter ("name", Name); Request.Set_Parameter ("comment", "Created wiki page " & Name); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("page-is-public", "1"); Request.Set_Parameter ("wiki-format", "FORMAT_MARKDOWN"); ASF.Tests.Do_Post (Request, Reply, "/wikis/create.html", "create-wiki.html"); T.Page_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/" & To_String (T.Wiki_Ident) & "/"); Util.Tests.Assert_Equals (T, Name, To_String (T.Page_Ident), "Invalid redirect after wiki page creation"); -- Remove the 'wikiPage' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("wikiPage"); end Create_Page; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Wiki Space Title"); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/wikis/setup.html", "setup-wiki.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after wiki space creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/list/"); Pos : constant Natural := Util.Strings.Index (Ident, '/'); begin Util.Tests.Assert_Matches (T, "^[0-9]+/recent/grid$", Ident, "Invalid wiki space identifier in the response"); T.Wiki_Ident := To_Unbounded_String (Ident (Ident'First .. Pos - 1)); end; Create_Page ("WikiPageTestName", "Wiki page title1"); T.Verify_List_Contains (To_String (T.Page_Ident)); Create_Page ("WikiSecondPageName", "Wiki page title2"); T.Verify_List_Contains (To_String (T.Page_Ident)); Create_Page ("WikiThirdPageName", "Wiki page title3"); T.Verify_Anonymous ("WikiPageTestName", "Wiki page title1"); T.Verify_Anonymous ("WikiSecondPageName", "Wiki page title2"); T.Verify_Anonymous ("WikiThirdPageName", "Wiki page title3"); end Test_Create_Wiki; -- ------------------------------ -- Test getting a wiki page which does not exist. -- ------------------------------ procedure Test_Missing_Page (T : in out Test) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/MissingPage", "wiki-page-missing.html"); ASF.Tests.Assert_Matches (T, ".title.Wiki page does not exist./title.", Reply, "Wiki page 'MissingPage' is invalid", ASF.Responses.SC_NOT_FOUND); ASF.Tests.Assert_Matches (T, ".h2.MissingPage./h2.", Reply, "Wiki page 'MissingPage' header is invalid", ASF.Responses.SC_NOT_FOUND); end Test_Missing_Page; end AWA.Wikis.Tests;
----------------------------------------------------------------------- -- awa-wikis-tests -- Unit tests for wikis module -- 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 Util.Test_Caller; with Util.Strings; with Servlet.Streams; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Wikis.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Wikis.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load_List (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save", Test_Create_Wiki'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (missing)", Test_Missing_Page'Access); end Add_Tests; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is function Get_Link (Title : in String) return String; Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; function Get_Link (Title : in String) return String is Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title); end Get_Link; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/wikis/tags/" & Wiki, "wiki-list-tagged.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki tag page is invalid"); if Page'Length > 0 then ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/" & Page, "wiki-page-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "The wiki page content", Reply, "Wiki page " & Page & " is invalid"); declare Info : constant String := Get_Link ("Info"); History : constant String := Get_Link ("History"); begin Util.Tests.Assert_Matches (T, "/asfunit/wikis/info/[0-9]+/[0-9]+$", Info, "Invalid wiki info link in the response"); Util.Tests.Assert_Matches (T, "/asfunit/wikis/history/[0-9]+/[0-9]+$", History, "Invalid wiki history link in the response"); -- Get the information page. ASF.Tests.Do_Get (Request, Reply, Info (Info'First + 8 .. Info'Last), "wiki-info-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-word-list", Reply, "Wiki info page " & Page & " is invalid"); -- Get the history page. ASF.Tests.Do_Get (Request, Reply, History (History'First + 8 .. History'Last), "wiki-history-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-page-version", Reply, "Wiki history page " & Page & " is invalid"); end; end if; end Verify_Anonymous; -- ------------------------------ -- Verify that the wiki lists contain the given page. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Page : in String) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list recent page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/popular", "wiki-list-popular.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list popular page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list popular page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name", "wiki-list-name.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name/grid", "wiki-list-name-grid.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name/grid page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name/grid page does not reference the page"); end Verify_List_Contains; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Wiki (T : in out Test) is procedure Create_Page (Name : in String; Title : in String); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; procedure Create_Page (Name : in String; Title : in String) is begin Request.Set_Parameter ("page-wiki-id", To_String (T.Wiki_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("page-title", Title); Request.Set_Parameter ("text", "# Main title" & ASCII.LF & "* The wiki page content." & ASCII.LF & "* Second item." & ASCII.LF); Request.Set_Parameter ("name", Name); Request.Set_Parameter ("comment", "Created wiki page " & Name); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("page-is-public", "1"); Request.Set_Parameter ("wiki-format", "FORMAT_MARKDOWN"); ASF.Tests.Do_Post (Request, Reply, "/wikis/create.html", "create-wiki.html"); T.Page_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/" & To_String (T.Wiki_Ident) & "/"); Util.Tests.Assert_Equals (T, Name, To_String (T.Page_Ident), "Invalid redirect after wiki page creation"); -- Remove the 'wikiPage' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("wikiPage"); end Create_Page; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Wiki Space Title"); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/wikis/setup.html", "setup-wiki.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after wiki space creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/list/"); Pos : constant Natural := Util.Strings.Index (Ident, '/'); begin Util.Tests.Assert_Matches (T, "^[0-9]+/recent/grid$", Ident, "Invalid wiki space identifier in the response"); T.Wiki_Ident := To_Unbounded_String (Ident (Ident'First .. Pos - 1)); end; Create_Page ("WikiPageTestName", "Wiki page title1"); T.Verify_List_Contains (To_String (T.Page_Ident)); Create_Page ("WikiSecondPageName", "Wiki page title2"); T.Verify_List_Contains (To_String (T.Page_Ident)); Create_Page ("WikiThirdPageName", "Wiki page title3"); T.Verify_Anonymous ("WikiPageTestName", "Wiki page title1"); T.Verify_Anonymous ("WikiSecondPageName", "Wiki page title2"); T.Verify_Anonymous ("WikiThirdPageName", "Wiki page title3"); end Test_Create_Wiki; -- ------------------------------ -- Test getting a wiki page which does not exist. -- ------------------------------ procedure Test_Missing_Page (T : in out Test) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/MissingPage", "wiki-page-missing.html"); ASF.Tests.Assert_Matches (T, ".title.Wiki page does not exist./title.", Reply, "Wiki page 'MissingPage' is invalid", ASF.Responses.SC_NOT_FOUND); ASF.Tests.Assert_Matches (T, ".h2.MissingPage./h2.", Reply, "Wiki page 'MissingPage' header is invalid", ASF.Responses.SC_NOT_FOUND); end Test_Missing_Page; end AWA.Wikis.Tests;
Rename the test for the results
Rename the test for the results
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1622aff9a2773fa965fd59299f02f3ba04747628
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; 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); Reader.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 (Reader, Data'Unchecked_Access); Reader.Parse (S); end; end loop; end XMI;
----------------------------------------------------------------------- -- 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;
Update the example to use the new parser/mapper interface
Update the example to use the new parser/mapper interface
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
01ba7b5ddcd919f49461a08a06372854390d3fe2
mat/src/memory/mat-memory.ads
mat/src/memory/mat-memory.ads
----------------------------------------------------------------------- -- Memory - Memory slot -- 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.Strings.Unbounded; with ELF; with MAT.Types; with MAT.Frames; with Interfaces; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; -- Statistics about memory allocation. type Memory_Info is record Total_Size : MAT.Types.Target_Size := 0; Alloc_Count : Natural := 0; Min_Slot_Size : MAT.Types.Target_Size := 0; Max_Slot_Size : MAT.Types.Target_Size := 0; Min_Addr : MAT.Types.Target_Addr := 0; Max_Addr : MAT.Types.Target_Addr := 0; end record; -- Description of a memory region. type Region_Info is record Start_Addr : MAT.Types.Target_Addr := 0; End_Addr : MAT.Types.Target_Addr := 0; Size : MAT.Types.Target_Size := 0; Flags : ELF.Elf32_Word := 0; Path : Ada.Strings.Unbounded.Unbounded_String; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; -- Define a map of <tt>Memory_Info</tt> keyed by the thread Id. -- Such map allows to give the list of threads and a summary of their allocation. use type MAT.Types.Target_Thread_Ref; package Memory_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref, Element_Type => Memory_Info); subtype Memory_Info_Map is Memory_Info_Maps.Map; subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor; type Frame_Info is record Thread : MAT.Types.Target_Thread_Ref; Memory : Memory_Info; end record; -- Define a map of <tt>Frame_Info</tt> keyed by the backtrace function address -- that performed the memory allocation directly or indirectly. package Frame_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Frame_Info); subtype Frame_Info_Map is Frame_Info_Maps.Map; subtype Frame_Info_Cursor is Frame_Info_Maps.Cursor; package Region_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Region_Info); subtype Region_Info_Map is Region_Info_Maps.Map; subtype Region_Info_Cursor is Region_Info_Maps.Cursor; private end MAT.Memory;
----------------------------------------------------------------------- -- Memory - Memory slot -- 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.Strings.Unbounded; with ELF; with MAT.Types; with MAT.Frames; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; -- Statistics about memory allocation. type Memory_Info is record Total_Size : MAT.Types.Target_Size := 0; Alloc_Count : Natural := 0; Min_Slot_Size : MAT.Types.Target_Size := 0; Max_Slot_Size : MAT.Types.Target_Size := 0; Min_Addr : MAT.Types.Target_Addr := 0; Max_Addr : MAT.Types.Target_Addr := 0; end record; -- Description of a memory region. type Region_Info is record Start_Addr : MAT.Types.Target_Addr := 0; End_Addr : MAT.Types.Target_Addr := 0; Size : MAT.Types.Target_Size := 0; Flags : ELF.Elf32_Word := 0; Path : Ada.Strings.Unbounded.Unbounded_String; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; -- Define a map of <tt>Memory_Info</tt> keyed by the thread Id. -- Such map allows to give the list of threads and a summary of their allocation. use type MAT.Types.Target_Thread_Ref; package Memory_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref, Element_Type => Memory_Info); subtype Memory_Info_Map is Memory_Info_Maps.Map; subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor; type Frame_Info is record Thread : MAT.Types.Target_Thread_Ref; Memory : Memory_Info; end record; -- Define a map of <tt>Frame_Info</tt> keyed by the backtrace function address -- that performed the memory allocation directly or indirectly. package Frame_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Frame_Info); subtype Frame_Info_Map is Frame_Info_Maps.Map; subtype Frame_Info_Cursor is Frame_Info_Maps.Cursor; package Region_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Region_Info); subtype Region_Info_Map is Region_Info_Maps.Map; subtype Region_Info_Cursor is Region_Info_Maps.Cursor; end MAT.Memory;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
54e3f6a7cc91afd2c4406bf1dd1abbdd4320e073
awa/plugins/awa-storages/src/awa-storages-servlets.adb
awa/plugins/awa-storages/src/awa-storages-servlets.adb
----------------------------------------------------------------------- -- awa-storages-servlets -- Serve files saved in the storage service -- Copyright (C) 2012, 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 Ada.Strings.Unbounded; with Util.Log.Loggers; with ADO.Objects; with Servlet.Routes; with ASF.Streams; with AWA.Storages.Services; with AWA.Storages.Modules; package body AWA.Storages.Servlets is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Servlets"); -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ overriding procedure Initialize (Server : in out Storage_Servlet; Context : in Servlet.Core.Servlet_Registry'Class) is begin null; end Initialize; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ overriding procedure Do_Get (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is type Get_Type is (DEFAULT, AS_CONTENT_DISPOSITION, INVALID); function Get_Format return Get_Type; function Get_Format return Get_Type is Format : constant String := Request.Get_Path_Parameter (2); begin if Format = "view" then return DEFAULT; elsif Format = "download" then return AS_CONTENT_DISPOSITION; else return INVALID; end if; end Get_Format; URI : constant String := Request.Get_Request_URI; Data : ADO.Blob_Ref; Mime : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; Format : Get_Type; begin Format := Get_Format; if Format = INVALID then Log.Info ("GET: {0}: invalid format", URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end if; Storage_Servlet'Class (Server).Load (Request, Name, Mime, Date, Data); if Data.Is_Null then Log.Info ("GET: {0}: storage file not found", URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end if; Log.Info ("GET: {0}", URI); -- Send the file. Response.Set_Content_Type (Ada.Strings.Unbounded.To_String (Mime)); if Format = AS_CONTENT_DISPOSITION and Ada.Strings.Unbounded.Length (Name) > 0 then Response.Add_Header ("Content-Disposition", "attachment; filename=" & Ada.Strings.Unbounded.To_String (Name)); end if; declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write (Data.Value.Data); end; exception when Servlet.Routes.No_Parameter => Log.Info ("GET: {0}: Invalid servlet-mapping, a path parameter is missing", URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; when ADO.Objects.NOT_FOUND | Constraint_Error => Log.Info ("GET: {0}: Storage file not found", URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end Do_Get; -- ------------------------------ -- Load the data content that correspond to the GET request and get the name as well -- as mime-type and date. -- ------------------------------ procedure Load (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Data : out ADO.Blob_Ref) is pragma Unreferenced (Server); Store : constant String := Request.Get_Path_Parameter (1); Manager : constant Services.Storage_Service_Access := Storages.Modules.Get_Storage_Manager; Id : ADO.Identifier; begin if Store'Length = 0 then Log.Info ("Invalid storage URI: {0}", Store); return; end if; -- Extract the storage identifier from the URI. Id := ADO.Identifier'Value (Store); Log.Info ("GET storage file {0}", Store); Manager.Load (From => Id, Name => Name, Mime => Mime, Date => Date, Into => Data); end Load; end AWA.Storages.Servlets;
----------------------------------------------------------------------- -- awa-storages-servlets -- Serve files saved in the storage service -- Copyright (C) 2012, 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 Ada.Strings.Unbounded; with Util.Log.Loggers; with ADO.Objects; with Servlet.Routes; with ASF.Streams; with AWA.Storages.Services; with AWA.Storages.Modules; package body AWA.Storages.Servlets is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Servlets"); -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ overriding procedure Initialize (Server : in out Storage_Servlet; Context : in Servlet.Core.Servlet_Registry'Class) is begin null; end Initialize; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ overriding procedure Do_Get (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is URI : constant String := Request.Get_Request_URI; Data : ADO.Blob_Ref; Mime : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; Format : Get_Type; begin Format := Storage_Servlet'Class (Server).Get_Format (Request); if Format = INVALID then Log.Info ("GET: {0}: invalid format", URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end if; Storage_Servlet'Class (Server).Load (Request, Name, Mime, Date, Data); if Data.Is_Null then Log.Info ("GET: {0}: storage file not found", URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end if; Log.Info ("GET: {0}", URI); -- Send the file. Response.Set_Content_Type (Ada.Strings.Unbounded.To_String (Mime)); if Format = AS_CONTENT_DISPOSITION and Ada.Strings.Unbounded.Length (Name) > 0 then Response.Add_Header ("Content-Disposition", "attachment; filename=" & Ada.Strings.Unbounded.To_String (Name)); end if; declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write (Data.Value.Data); end; exception when Servlet.Routes.No_Parameter => Log.Info ("GET: {0}: Invalid servlet-mapping, a path parameter is missing", URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; when ADO.Objects.NOT_FOUND | Constraint_Error => Log.Info ("GET: {0}: Storage file not found", URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end Do_Get; -- ------------------------------ -- Load the data content that correspond to the GET request and get the name as well -- as mime-type and date. -- ------------------------------ procedure Load (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Data : out ADO.Blob_Ref) is pragma Unreferenced (Server); Store : constant String := Request.Get_Path_Parameter (1); Manager : constant Services.Storage_Service_Access := Storages.Modules.Get_Storage_Manager; Id : ADO.Identifier; begin if Store'Length = 0 then Log.Info ("Invalid storage URI: {0}", Store); return; end if; -- Extract the storage identifier from the URI. Id := ADO.Identifier'Value (Store); Log.Info ("GET storage file {0}", Store); Manager.Load (From => Id, Name => Name, Mime => Mime, Date => Date, Into => Data); end Load; -- ------------------------------ -- Get the expected return mode (content disposition for download or inline). -- ------------------------------ function Get_Format (Server : in Storage_Servlet; Request : in ASF.Requests.Request'Class) return Get_Type is pragma Unreferenced (Server); Format : constant String := Request.Get_Path_Parameter (2); begin if Format = "view" then return DEFAULT; elsif Format = "download" then return AS_CONTENT_DISPOSITION; else return INVALID; end if; end Get_Format; end AWA.Storages.Servlets;
Move the internal Get_Format function a visible and overridable function of Storage_Servlet
Move the internal Get_Format function a visible and overridable function of Storage_Servlet
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1775523c4f082c6371af466f9165cfafeced9d62
src/ado-sql.ads
src/ado-sql.ads
----------------------------------------------------------------------- -- ADO SQL -- Basic SQL Generation -- Copyright (C) 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Util.Strings; with ADO.Parameters; with ADO.Drivers.Dialects; -- Utilities for creating SQL queries and statements. package ADO.SQL is use Ada.Strings.Unbounded; -- -------------------- -- Buffer -- -------------------- -- The <b>Buffer</b> type allows to build easily an SQL statement. -- type Buffer is private; type Buffer_Access is access all Buffer; -- Clear the SQL buffer. procedure Clear (Target : in out Buffer); -- Append an SQL extract into the buffer. procedure Append (Target : in out Buffer; SQL : in String); -- Append a name in the buffer and escape that -- name if this is a reserved keyword. procedure Append_Name (Target : in out Buffer; Name : in String); -- Append a string value in the buffer and -- escape any special character if necessary. procedure Append_Value (Target : in out Buffer; Value : in String); -- Append a string value in the buffer and -- escape any special character if necessary. procedure Append_Value (Target : in out Buffer; Value : in Unbounded_String); -- Append the integer value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Long_Integer); -- Append the integer value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Integer); -- Append the identifier value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Identifier); -- Get the SQL string that was accumulated in the buffer. function To_String (From : in Buffer) return String; -- -------------------- -- Query -- -------------------- -- The <b>Query</b> type contains the elements for building and -- executing the request. This includes: -- <ul> -- <li>The SQL request (full request or a fragment)</li> -- <li>The SQL request parameters </li> -- <li>An SQL filter condition</li> -- </ul> -- type Query is new ADO.Parameters.List with record SQL : Buffer; Filter : Buffer; Join : Buffer; end record; type Query_Access is access all Query'Class; -- Clear the query object. overriding procedure Clear (Target : in out Query); -- Set the SQL dialect description object. procedure Set_Dialect (Target : in out Query; D : in ADO.Drivers.Dialects.Dialect_Access); procedure Set_Filter (Target : in out Query; Filter : in String); function Has_Filter (Source : in Query) return Boolean; function Get_Filter (Source : in Query) return String; -- Set the join condition. procedure Set_Join (Target : in out Query; Join : in String); -- Returns true if there is a join condition function Has_Join (Source : in Query) return Boolean; -- Get the join condition function Get_Join (Source : in Query) return String; -- Set the parameters from another parameter list. -- If the parameter list is a query object, also copy the filter part. procedure Set_Parameters (Params : in out Query; From : in ADO.Parameters.Abstract_List'Class); -- Expand the parameters into the query and return the expanded SQL query. function Expand (Source : in Query) return String; -- -------------------- -- Update Query -- -------------------- -- The <b>Update_Query</b> provides additional helper functions to construct -- and <i>insert</i> or an <i>update</i> statement. type Update_Query is new Query with private; type Update_Query_Access is access all Update_Query'Class; -- Set the SQL dialect description object. procedure Set_Dialect (Target : in out Update_Query; D : in ADO.Drivers.Dialects.Dialect_Access); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Boolean); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Integer); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Long_Long_Integer); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Identifier); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Entity_Type); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Ada.Calendar.Time); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in String); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Unbounded_String); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in ADO.Blob_Ref); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to NULL. procedure Save_Null_Field (Update : in out Update_Query; Name : in String); -- Check if the update/insert query has some fields to update. function Has_Save_Fields (Update : in Update_Query) return Boolean; procedure Set_Insert_Mode (Update : in out Update_Query); procedure Append_Fields (Update : in out Update_Query; Mode : in Boolean := False); private type Buffer is new ADO.Parameters.List with record Buf : Unbounded_String; end record; type Update_Query is new Query with record Pos : Natural := 0; Set_Fields : Buffer; Fields : Buffer; Is_Update_Stmt : Boolean := True; end record; procedure Add_Field (Update : in out Update_Query'Class; Name : in String); end ADO.SQL;
----------------------------------------------------------------------- -- ADO SQL -- Basic SQL Generation -- Copyright (C) 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with ADO.Parameters; with ADO.Drivers.Dialects; -- Utilities for creating SQL queries and statements. package ADO.SQL is use Ada.Strings.Unbounded; -- -------------------- -- Buffer -- -------------------- -- The <b>Buffer</b> type allows to build easily an SQL statement. -- type Buffer is private; type Buffer_Access is access all Buffer; -- Clear the SQL buffer. procedure Clear (Target : in out Buffer); -- Append an SQL extract into the buffer. procedure Append (Target : in out Buffer; SQL : in String); -- Append a name in the buffer and escape that -- name if this is a reserved keyword. procedure Append_Name (Target : in out Buffer; Name : in String); -- Append a string value in the buffer and -- escape any special character if necessary. procedure Append_Value (Target : in out Buffer; Value : in String); -- Append a string value in the buffer and -- escape any special character if necessary. procedure Append_Value (Target : in out Buffer; Value : in Unbounded_String); -- Append the integer value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Long_Integer); -- Append the integer value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Integer); -- Append the identifier value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Identifier); -- Get the SQL string that was accumulated in the buffer. function To_String (From : in Buffer) return String; -- -------------------- -- Query -- -------------------- -- The <b>Query</b> type contains the elements for building and -- executing the request. This includes: -- <ul> -- <li>The SQL request (full request or a fragment)</li> -- <li>The SQL request parameters </li> -- <li>An SQL filter condition</li> -- </ul> -- type Query is new ADO.Parameters.List with record SQL : Buffer; Filter : Buffer; Join : Buffer; end record; type Query_Access is access all Query'Class; -- Clear the query object. overriding procedure Clear (Target : in out Query); -- Set the SQL dialect description object. procedure Set_Dialect (Target : in out Query; D : in ADO.Drivers.Dialects.Dialect_Access); procedure Set_Filter (Target : in out Query; Filter : in String); function Has_Filter (Source : in Query) return Boolean; function Get_Filter (Source : in Query) return String; -- Set the join condition. procedure Set_Join (Target : in out Query; Join : in String); -- Returns true if there is a join condition function Has_Join (Source : in Query) return Boolean; -- Get the join condition function Get_Join (Source : in Query) return String; -- Set the parameters from another parameter list. -- If the parameter list is a query object, also copy the filter part. procedure Set_Parameters (Params : in out Query; From : in ADO.Parameters.Abstract_List'Class); -- Expand the parameters into the query and return the expanded SQL query. function Expand (Source : in Query) return String; -- -------------------- -- Update Query -- -------------------- -- The <b>Update_Query</b> provides additional helper functions to construct -- and <i>insert</i> or an <i>update</i> statement. type Update_Query is new Query with private; type Update_Query_Access is access all Update_Query'Class; -- Set the SQL dialect description object. procedure Set_Dialect (Target : in out Update_Query; D : in ADO.Drivers.Dialects.Dialect_Access); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Boolean); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Integer); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Long_Long_Integer); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Identifier); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Entity_Type); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Ada.Calendar.Time); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in String); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Unbounded_String); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in ADO.Blob_Ref); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to NULL. procedure Save_Null_Field (Update : in out Update_Query; Name : in String); -- Check if the update/insert query has some fields to update. function Has_Save_Fields (Update : in Update_Query) return Boolean; procedure Set_Insert_Mode (Update : in out Update_Query); procedure Append_Fields (Update : in out Update_Query; Mode : in Boolean := False); private type Buffer is new ADO.Parameters.List with record Buf : Unbounded_String; end record; type Update_Query is new Query with record Pos : Natural := 0; Set_Fields : Buffer; Fields : Buffer; Is_Update_Stmt : Boolean := True; end record; procedure Add_Field (Update : in out Update_Query'Class; Name : in String); end ADO.SQL;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-ado
18b383fbc7c2356f0d0aa5087dcb19653d5fa99c
src/el-utils.adb
src/el-utils.adb
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Objects; with EL.Expressions; with EL.Contexts.Default; with EL.Contexts.Properties; package body EL.Utils is use Util.Log; use Ada.Strings.Unbounded; use Util.Beans.Objects; -- The logger Log : constant Loggers.Logger := Loggers.Create ("EL.Utils"); -- ------------------------------ -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). -- ------------------------------ procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class) is function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. procedure Process (Name, Item : in Util.Properties.Value); type Local_Resolver is new EL.Contexts.Properties.Property_Resolver with null record; -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object is pragma Unreferenced (Resolver); begin if Base /= null then return Base.Get_Value (To_String (Name)); elsif Into.Exists (Name) then return Util.Beans.Objects.To_Object (String '(Into.Get (Name))); elsif Source.Exists (Name) then declare Value : constant String := Source.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; Recursion : Natural := 10; -- ------------------------------ -- Expand (recursively) the EL expression defined in <b>Value</b> by using -- the context. The recursion is provided by the above context resolver which -- invokes <b>Expand</b> if it detects that a value is a possible EL expression. -- ------------------------------ function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin if Recursion = 0 then Log.Error ("Too many level of recursion when evaluating expression: {0}", Value); return Util.Beans.Objects.Null_Object; end if; Recursion := Recursion - 1; Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); Recursion := Recursion + 1; return Result; -- Ignore any exception and copy the value verbatim. exception when others => Recursion := Recursion + 1; return Util.Beans.Objects.To_Object (Value); end Expand; Resolver : aliased Local_Resolver; Local_Context : aliased EL.Contexts.Default.Default_Context; -- ------------------------------ -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. -- ------------------------------ procedure Process (Name, Item : in Util.Properties.Value) is use Ada.Strings; begin if Unbounded.Index (Item, "{") = 0 or Unbounded.Index (Item, "{") = 0 then Log.Debug ("Adding config {0} = {1}", Name, Item); Into.Set (Name, Item); else declare Value : constant Object := Expand (To_String (Item), Local_Context); Val : Unbounded_String; begin if not Util.Beans.Objects.Is_Null (Value) then Val := Util.Beans.Objects.To_Unbounded_String (Value); end if; Log.Debug ("Adding config {0} = {1}", Name, Val); Into.Set (Name, Val); end; end if; end Process; begin Resolver.Set_Properties (Source); Local_Context.Set_Function_Mapper (Context.Get_Function_Mapper); Local_Context.Set_Resolver (Resolver'Unchecked_Access); Source.Iterate (Process'Access); end Expand; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); return Util.Beans.Objects.To_String (Result); -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (Value, Context); return Expr.Get_Value (Context); -- Ignore any exception and copy the value verbatim. exception when others => return Util.Beans.Objects.To_Object (Value); end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is begin case Util.Beans.Objects.Get_Type (Value) is when Util.Beans.Objects.TYPE_STRING | Util.Beans.Objects.TYPE_WIDE_STRING => declare S : constant String := Util.Beans.Objects.To_String (Value); Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (S, Context); return Expr.Get_Value (Context); end; when others => return Value; end case; -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; end EL.Utils;
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Objects; with EL.Expressions; with EL.Contexts.Default; with EL.Contexts.Properties; package body EL.Utils is use Util.Log; use Ada.Strings.Unbounded; use Util.Beans.Objects; -- The logger Log : constant Loggers.Logger := Loggers.Create ("EL.Utils"); -- ------------------------------ -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). -- ------------------------------ procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class) is function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. procedure Process (Name, Item : in Util.Properties.Value); type Local_Resolver is new EL.Contexts.Properties.Property_Resolver with null record; -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object is pragma Unreferenced (Resolver); begin if Base /= null then return Base.Get_Value (To_String (Name)); elsif Into.Exists (Name) then declare Value : constant String := Into.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; elsif Source.Exists (Name) then declare Value : constant String := Source.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; Recursion : Natural := 10; -- ------------------------------ -- Expand (recursively) the EL expression defined in <b>Value</b> by using -- the context. The recursion is provided by the above context resolver which -- invokes <b>Expand</b> if it detects that a value is a possible EL expression. -- ------------------------------ function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin if Recursion = 0 then Log.Error ("Too many level of recursion when evaluating expression: {0}", Value); return Util.Beans.Objects.Null_Object; end if; Recursion := Recursion - 1; Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); Recursion := Recursion + 1; return Result; -- Ignore any exception and copy the value verbatim. exception when others => Recursion := Recursion + 1; return Util.Beans.Objects.To_Object (Value); end Expand; Resolver : aliased Local_Resolver; Local_Context : aliased EL.Contexts.Default.Default_Context; -- ------------------------------ -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. -- ------------------------------ procedure Process (Name, Item : in Util.Properties.Value) is use Ada.Strings; begin if Unbounded.Index (Item, "{") = 0 or Unbounded.Index (Item, "{") = 0 then Log.Debug ("Adding config {0} = {1}", Name, Item); Into.Set (Name, Item); else declare Value : constant Object := Expand (To_String (Item), Local_Context); Val : Unbounded_String; begin if not Util.Beans.Objects.Is_Null (Value) then Val := Util.Beans.Objects.To_Unbounded_String (Value); end if; Log.Debug ("Adding config {0} = {1}", Name, Val); Into.Set (Name, Val); end; end if; end Process; begin Resolver.Set_Properties (Source); Local_Context.Set_Function_Mapper (Context.Get_Function_Mapper); Local_Context.Set_Resolver (Resolver'Unchecked_Access); Source.Iterate (Process'Access); end Expand; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); return Util.Beans.Objects.To_String (Result); -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (Value, Context); return Expr.Get_Value (Context); -- Ignore any exception and copy the value verbatim. exception when others => return Util.Beans.Objects.To_Object (Value); end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is begin case Util.Beans.Objects.Get_Type (Value) is when Util.Beans.Objects.TYPE_STRING | Util.Beans.Objects.TYPE_WIDE_STRING => declare S : constant String := Util.Beans.Objects.To_String (Value); Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (S, Context); return Expr.Get_Value (Context); end; when others => return Value; end case; -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; end EL.Utils;
Fix evaluation of properties when Source and Into are the same sets If the value from Into is a possible EL expression, perform a recursive expand of that value.
Fix evaluation of properties when Source and Into are the same sets If the value from Into is a possible EL expression, perform a recursive expand of that value.
Ada
apache-2.0
stcarrez/ada-el
2e51330d817ea03c70c686631afd9d0ffffdaa19
mat/src/gtk/mat-callbacks.adb
mat/src/gtk/mat-callbacks.adb
----------------------------------------------------------------------- -- mat-callbacks - Callbacks for Gtk -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Gtk.Main; package body MAT.Callbacks is -- ------------------------------ -- Callback executed when the "quit" action is executed from the menu. -- ------------------------------ procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is begin Gtk.Main.Main_Quit; end On_Menu_Quit; end MAT.Callbacks;
----------------------------------------------------------------------- -- mat-callbacks - Callbacks for Gtk -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Gtk.Main; with Gtk.Widget; package body MAT.Callbacks is -- ------------------------------ -- Callback executed when the "quit" action is executed from the menu. -- ------------------------------ procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is begin Gtk.Main.Main_Quit; end On_Menu_Quit; -- ------------------------------ -- Callback executed when the "about" action is executed from the menu. -- ------------------------------ procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is About : constant Gtk.Widget.Gtk_Widget := Gtk.Widget.Gtk_Widget (Object.Get_Object ("about")); begin About.Show; end On_Menu_About; end MAT.Callbacks;
Implement the On_Menu_About procedure
Implement the On_Menu_About procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
fc6b92e899c8a948f83e7fb0af1f38b88926d1f1
regtests/util-beans-objects-record_tests.adb
regtests/util-beans-objects-record_tests.adb
----------------------------------------------------------------------- -- util-beans-objects-record_tests -- Unit tests for objects.records package -- Copyright (C) 2011, 2017, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with Util.Beans.Basic; with Util.Beans.Objects.Vectors; with Util.Beans.Objects.Records; package body Util.Beans.Objects.Record_Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Beans.Records"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.Records", Test_Record'Access); Caller.Add_Test (Suite, "Test Util.Beans.Basic", Test_Bean'Access); end Add_Tests; type Data is record Name : Unbounded_String; Value : Util.Beans.Objects.Object; end record; package Data_Bean is new Util.Beans.Objects.Records (Data); use type Data_Bean.Element_Type_Access; subtype Data_Access is Data_Bean.Element_Type_Access; procedure Test_Record (T : in out Test) is D : Data; begin D.Name := To_Unbounded_String ("testing"); D.Value := To_Object (Integer (23)); declare V : Object := Data_Bean.To_Object (D); P : constant Data_Access := Data_Bean.To_Element_Access (V); V2 : constant Object := V; begin T.Assert (not Is_Empty (V), "Object with data record should not be empty"); T.Assert (not Is_Null (V), "Object with data record should not be null"); T.Assert (P /= null, "To_Element_Access returned null"); Assert_Equals (T, "testing", To_String (P.Name), "Data name is not the same"); Assert_Equals (T, 23, To_Integer (P.Value), "Data value is not the same"); V := Data_Bean.Create; declare D2 : constant Data_Access := Data_Bean.To_Element_Access (V); begin T.Assert (D2 /= null, "Null element"); D2.Name := To_Unbounded_String ("second test"); D2.Value := V2; end; V := Data_Bean.To_Object (D); end; end Test_Record; type Bean_Type is new Util.Beans.Basic.Readonly_Bean with record Name : Unbounded_String; end record; type Bean_Type_Access is access all Bean_Type'Class; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); elsif Name = "length" then return Util.Beans.Objects.To_Object (Length (Bean.Name)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; procedure Test_Bean (T : in out Test) is use Basic; Static : aliased Bean_Type; begin Static.Name := To_Unbounded_String ("Static"); -- Allocate dynamically several Bean_Type objects and drop the list. -- The memory held by internal proxy as well as the Bean_Type must be freed. -- The static bean should never be freed! for I in 1 .. 10 loop declare List : Util.Beans.Objects.Vectors.Vector; Value : Util.Beans.Objects.Object; Bean : Bean_Type_Access; P : access Readonly_Bean'Class; begin for J in 1 .. 1_000 loop if I = J then Value := To_Object (Static'Unchecked_Access, Objects.STATIC); List.Append (Value); end if; Bean := new Bean_Type; Bean.Name := To_Unbounded_String ("B" & Util.Strings.Image (J)); Value := To_Object (Bean); List.Append (Value); end loop; -- Verify each bean of the list for J in 1 .. 1_000 + 1 loop Value := List.Element (J); -- Check some common status. T.Assert (not Is_Null (Value), "The value should hold a bean"); T.Assert (Get_Type (Value) = TYPE_BEAN, "The value should hold a bean"); T.Assert (not Is_Empty (Value), "The value should not be empty"); -- Check the bean access. P := To_Bean (Value); T.Assert (P /= null, "To_Bean returned null"); Bean := Bean_Type'Class (P.all)'Unchecked_Access; -- Check we have the good bean object. if I = J then Assert_Equals (T, "Static", To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); elsif J > I then Assert_Equals (T, "B" & Util.Strings.Image (J - 1), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); else Assert_Equals (T, "B" & Util.Strings.Image (J), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); end if; end loop; end; end loop; end Test_Bean; end Util.Beans.Objects.Record_Tests;
----------------------------------------------------------------------- -- util-beans-objects-record_tests -- Unit tests for objects.records package -- Copyright (C) 2011, 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 Util.Test_Caller; with Util.Strings; with Util.Beans.Basic; with Util.Beans.Objects.Vectors; with Util.Beans.Objects.Records; package body Util.Beans.Objects.Record_Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Beans.Records"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.Records", Test_Record'Access); Caller.Add_Test (Suite, "Test Util.Beans.Basic", Test_Bean'Access); end Add_Tests; type Data is record Name : Unbounded_String; Value : Util.Beans.Objects.Object; end record; package Data_Bean is new Util.Beans.Objects.Records (Data); use type Data_Bean.Element_Type_Access; subtype Data_Access is Data_Bean.Element_Type_Access; procedure Test_Record (T : in out Test) is D : Data; begin D.Name := To_Unbounded_String ("testing"); D.Value := To_Object (Integer (23)); declare V : Object := Data_Bean.To_Object (D); P : constant Data_Access := Data_Bean.To_Element_Access (V); V2 : constant Object := V; begin T.Assert (not Is_Empty (V), "Object with data record should not be empty"); T.Assert (not Is_Null (V), "Object with data record should not be null"); T.Assert (P /= null, "To_Element_Access returned null"); Assert_Equals (T, "testing", To_String (P.Name), "Data name is not the same"); Assert_Equals (T, 23, To_Integer (P.Value), "Data value is not the same"); V := Data_Bean.Create; declare D2 : constant Data_Access := Data_Bean.To_Element_Access (V); begin T.Assert (D2 /= null, "Null element"); D2.Name := To_Unbounded_String ("second test"); D2.Value := V2; end; V := Data_Bean.To_Object (D); Assert_Equals (T, "<UTIL.BEANS.OBJECTS.RECORD_TESTS.DATA_BEAN.ELEMENT_PROXY>", To_String (V), "Data name is not the same"); end; end Test_Record; type Bean_Type is new Util.Beans.Basic.Readonly_Bean with record Name : Unbounded_String; end record; type Bean_Type_Access is access all Bean_Type'Class; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); elsif Name = "length" then return Util.Beans.Objects.To_Object (Length (Bean.Name)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; procedure Test_Bean (T : in out Test) is use Basic; Static : aliased Bean_Type; begin Static.Name := To_Unbounded_String ("Static"); -- Allocate dynamically several Bean_Type objects and drop the list. -- The memory held by internal proxy as well as the Bean_Type must be freed. -- The static bean should never be freed! for I in 1 .. 10 loop declare List : Util.Beans.Objects.Vectors.Vector; Value : Util.Beans.Objects.Object; Bean : Bean_Type_Access; P : access Readonly_Bean'Class; begin for J in 1 .. 1_000 loop if I = J then Value := To_Object (Static'Unchecked_Access, Objects.STATIC); List.Append (Value); end if; Bean := new Bean_Type; Bean.Name := To_Unbounded_String ("B" & Util.Strings.Image (J)); Value := To_Object (Bean); List.Append (Value); end loop; -- Verify each bean of the list for J in 1 .. 1_000 + 1 loop Value := List.Element (J); -- Check some common status. T.Assert (not Is_Null (Value), "The value should hold a bean"); T.Assert (Get_Type (Value) = TYPE_BEAN, "The value should hold a bean"); T.Assert (not Is_Empty (Value), "The value should not be empty"); -- Check the bean access. P := To_Bean (Value); T.Assert (P /= null, "To_Bean returned null"); Bean := Bean_Type'Class (P.all)'Unchecked_Access; -- Check we have the good bean object. if I = J then Assert_Equals (T, "Static", To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); elsif J > I then Assert_Equals (T, "B" & Util.Strings.Image (J - 1), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); else Assert_Equals (T, "B" & Util.Strings.Image (J), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); end if; end loop; end; end loop; end Test_Bean; end Util.Beans.Objects.Record_Tests;
Add a new test for To_String on the record object
Add a new test for To_String on the record object
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5819c409fdd015efb30b50447917b747db31f721
samples/asf_volume_server.adb
samples/asf_volume_server.adb
----------------------------------------------------------------------- -- asf_volume_server -- The volume_server application with Ada Server Faces -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Server.Web; with ASF.Servlets; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Filters.Dump; with ASF.Applications; with ASF.Applications.Main; with EL.Objects; with Volume; procedure Asf_Volume_Server is CONTEXT_PATH : constant String := "/volume"; Factory : ASF.Applications.Main.Application_Factory; App : aliased ASF.Applications.Main.Application; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Bean : aliased Volume.Compute_Bean; Conv : constant access Volume.Float_Converter := new Volume.Float_Converter; WS : ASF.Server.Web.AWS_Container; C : ASF.Applications.Config; begin Bean.Radius := 1.2; Bean.Height := 2.0; C.Set (ASF.Applications.VIEW_EXT, ".html"); C.Set (ASF.Applications.VIEW_DIR, "samples/web"); C.Set ("web.dir", "samples/web"); App.Initialize (C, Factory); App.Set_Global ("contextPath", CONTEXT_PATH); App.Set_Global ("compute", EL.Objects.To_Object (Bean'Unchecked_Access)); -- Register the servlets and filters App.Add_Servlet (Name => "compute", Server => Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "compute", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Converter (Name => "float", Converter => Conv.all'Unchecked_Access); WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access); WS.Start; delay 600.0; end Asf_Volume_Server;
----------------------------------------------------------------------- -- asf_volume_server -- The volume_server application with Ada Server Faces -- 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 ASF.Server.Web; with ASF.Servlets; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Filters.Dump; with ASF.Applications; with ASF.Applications.Main; with Util.Beans.Objects; with Volume; procedure Asf_Volume_Server is CONTEXT_PATH : constant String := "/volume"; Factory : ASF.Applications.Main.Application_Factory; App : aliased ASF.Applications.Main.Application; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Bean : aliased Volume.Compute_Bean; Conv : constant access Volume.Float_Converter := new Volume.Float_Converter; WS : ASF.Server.Web.AWS_Container; C : ASF.Applications.Config; begin Bean.Radius := 1.2; Bean.Height := 2.0; C.Set (ASF.Applications.VIEW_EXT, ".html"); C.Set (ASF.Applications.VIEW_DIR, "samples/web"); C.Set ("web.dir", "samples/web"); App.Initialize (C, Factory); App.Set_Global ("contextPath", CONTEXT_PATH); App.Set_Global ("faces", Util.Beans.Objects.To_Object (Bean'Unchecked_Access)); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Converter (Name => "float", Converter => Conv.all'Unchecked_Access); WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access); WS.Start; delay 600.0; end Asf_Volume_Server;
Rename servlet and cleanup
Rename servlet and cleanup
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
f7c8b9a193f039f0371d688262c676648c687a8f
samples/wget.adb
samples/wget.adb
----------------------------------------------------------------------- -- wget -- A simple wget command to fetch a page -- 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.Strings; with Util.Strings.Tokenizers; with Util.Http.Clients; with Util.Http.Clients.Curl; procedure Wget is procedure Print_Token (Token : in String; Done : out Boolean) is begin Ada.Text_IO.Put_Line (Token); Done := False; end Print_Token; Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: wget url ..."); Ada.Text_IO.Put_Line ("Example: wget http://www.adacore.com"); return; end if; Util.Http.Clients.Curl.Register; for I in 1 .. Count loop declare Http : Util.Http.Clients.Client; URI : constant String := Ada.Command_Line.Argument (1); Response : Util.Http.Clients.Response; begin Http.Add_Header ("X-Requested-By", "wget"); Http.Get (URI, Response); Ada.Text_IO.Put_Line ("Code: " & Natural'Image (Response.Get_Status)); Ada.Text_IO.Put_Line (Response.Get_Body); end; end loop; end Wget;
----------------------------------------------------------------------- -- wget -- A simple wget command to fetch a page -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Util.Http.Clients; with Util.Http.Clients.Curl; procedure Wget is Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: wget url ..."); Ada.Text_IO.Put_Line ("Example: wget http://www.adacore.com"); return; end if; Util.Http.Clients.Curl.Register; for I in 1 .. Count loop declare Http : Util.Http.Clients.Client; URI : constant String := Ada.Command_Line.Argument (1); Response : Util.Http.Clients.Response; begin Http.Add_Header ("X-Requested-By", "wget"); Http.Get (URI, Response); Ada.Text_IO.Put_Line ("Code: " & Natural'Image (Response.Get_Status)); Ada.Text_IO.Put_Line (Response.Get_Body); end; end loop; end Wget;
Remove unused Print_Token operation
Remove unused Print_Token operation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a1c781010d6eb9be8ecf7043d8a86f9ab6a0337a
awa/src/awa-events-queues.adb
awa/src/awa-events-queues.adb
----------------------------------------------------------------------- -- awa-events-queues -- AWA Event Queues -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Serialize.Mappers; with AWA.Events.Queues.Fifos; with AWA.Events.Queues.Persistents; package body AWA.Events.Queues is -- ------------------------------ -- Queue the event. -- ------------------------------ procedure Enqueue (Into : in Queue_Ref; Event : in AWA.Events.Module_Event'Class) is Q : constant Queue_Info_Access := Into.Value; begin if Q = null or else Q.Queue = null then return; end if; Q.Queue.Enqueue (Event); end Enqueue; -- ------------------------------ -- Dequeue an event and process it with the <b>Process</b> procedure. -- ------------------------------ procedure Dequeue (From : in Queue_Ref; Process : access procedure (Event : in Module_Event'Class)) is Q : constant Queue_Info_Access := From.Value; begin if Q = null or else Q.Queue = null then return; end if; Q.Queue.Dequeue (Process); end Dequeue; -- ------------------------------ -- Returns true if the reference does not contain any element. -- ------------------------------ function Is_Null (Queue : in Queue_Ref'Class) return Boolean is Q : constant Queue_Info_Access := Queue.Value; begin return Q = null or else Q.Queue = null; end Is_Null; -- ------------------------------ -- Returns the queue name. -- ------------------------------ function Get_Name (Queue : in Queue_Ref'Class) return String is Q : constant Queue_Info_Access := Queue.Value; begin if Q = null then return ""; else return Q.Name; end if; end Get_Name; -- ------------------------------ -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. -- ------------------------------ function Get_Queue (Queue : in Queue_Ref'Class) return AWA.Events.Models.Queue_Ref is Q : constant Queue_Info_Access := Queue.Value; begin if Q = null or else Q.Queue = null then return AWA.Events.Models.Null_Queue; else return Q.Queue.Get_Queue; end if; end Get_Queue; FIFO_QUEUE_TYPE : constant String := "fifo"; PERSISTENT_QUEUE_TYPE : constant String := "persist"; -- ------------------------------ -- Create the event queue identified by the name <b>Name</b>. The queue factory -- identified by <b>Kind</b> is called to create the event queue instance. -- Returns a reference to the queue. -- ------------------------------ function Create_Queue (Name : in String; Kind : in String; Props : in EL.Beans.Param_Vectors.Vector; Context : in EL.Contexts.ELContext'Class) return Queue_Ref is Result : Queue_Ref; Q : constant Queue_Info_Access := new Queue_Info '(Util.Refs.Ref_Entity with Length => Name'Length, Name => Name, others => <>); begin Queue_Refs.Ref (Result) := Queue_Refs.Create (Q); if Kind = FIFO_QUEUE_TYPE then Q.Queue := AWA.Events.Queues.Fifos.Create_Queue (Name, Props, Context); elsif Name = PERSISTENT_QUEUE_TYPE then Q.Queue := AWA.Events.Queues.Persistents.Create_Queue (Name, Props, Context); else raise Util.Serialize.Mappers.Field_Error with "Invalid queue type: " & Name; end if; return Result; end Create_Queue; function Null_Queue return Queue_Ref is Result : Queue_Ref; begin return Result; end Null_Queue; -- ------------------------------ -- Finalize the referenced object. This is called before the object is freed. -- ------------------------------ overriding procedure Finalize (Object : in out Queue_Info) is procedure Free is new Ada.Unchecked_Deallocation (Object => Queue'Class, Name => Queue_Access); begin if Object.Queue /= null then Object.Queue.Finalize; Free (Object.Queue); end if; end Finalize; end AWA.Events.Queues;
----------------------------------------------------------------------- -- awa-events-queues -- AWA Event Queues -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Serialize.Mappers; with AWA.Events.Queues.Fifos; with AWA.Events.Queues.Persistents; package body AWA.Events.Queues is -- ------------------------------ -- Queue the event. -- ------------------------------ procedure Enqueue (Into : in Queue_Ref; Event : in AWA.Events.Module_Event'Class) is Q : constant Queue_Info_Access := Into.Value; begin if Q = null or else Q.Queue = null then return; end if; Q.Queue.Enqueue (Event); end Enqueue; -- ------------------------------ -- Dequeue an event and process it with the <b>Process</b> procedure. -- ------------------------------ procedure Dequeue (From : in Queue_Ref; Process : access procedure (Event : in Module_Event'Class)) is Q : constant Queue_Info_Access := From.Value; begin if Q = null or else Q.Queue = null then return; end if; Q.Queue.Dequeue (Process); end Dequeue; -- ------------------------------ -- Returns true if the reference does not contain any element. -- ------------------------------ function Is_Null (Queue : in Queue_Ref'Class) return Boolean is Q : constant Queue_Info_Access := Queue.Value; begin return Q = null or else Q.Queue = null; end Is_Null; -- ------------------------------ -- Returns the queue name. -- ------------------------------ function Get_Name (Queue : in Queue_Ref'Class) return String is Q : constant Queue_Info_Access := Queue.Value; begin if Q = null then return ""; else return Q.Name; end if; end Get_Name; -- ------------------------------ -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. -- ------------------------------ function Get_Queue (Queue : in Queue_Ref'Class) return AWA.Events.Models.Queue_Ref is Q : constant Queue_Info_Access := Queue.Value; begin if Q = null or else Q.Queue = null then return AWA.Events.Models.Null_Queue; else return Q.Queue.Get_Queue; end if; end Get_Queue; FIFO_QUEUE_TYPE : constant String := "fifo"; PERSISTENT_QUEUE_TYPE : constant String := "persist"; -- ------------------------------ -- Create the event queue identified by the name <b>Name</b>. The queue factory -- identified by <b>Kind</b> is called to create the event queue instance. -- Returns a reference to the queue. -- ------------------------------ function Create_Queue (Name : in String; Kind : in String; Props : in EL.Beans.Param_Vectors.Vector; Context : in EL.Contexts.ELContext'Class) return Queue_Ref is Result : Queue_Ref; Q : constant Queue_Info_Access := new Queue_Info '(Util.Refs.Ref_Entity with Length => Name'Length, Name => Name, others => <>); begin Queue_Refs.Ref (Result) := Queue_Refs.Create (Q); if Kind = FIFO_QUEUE_TYPE then Q.Queue := AWA.Events.Queues.Fifos.Create_Queue (Name, Props, Context); elsif Kind = PERSISTENT_QUEUE_TYPE then Q.Queue := AWA.Events.Queues.Persistents.Create_Queue (Name, Props, Context); else raise Util.Serialize.Mappers.Field_Error with "Invalid queue type: " & Kind; end if; return Result; end Create_Queue; function Null_Queue return Queue_Ref is Result : Queue_Ref; begin return Result; end Null_Queue; -- ------------------------------ -- Finalize the referenced object. This is called before the object is freed. -- ------------------------------ overriding procedure Finalize (Object : in out Queue_Info) is procedure Free is new Ada.Unchecked_Deallocation (Object => Queue'Class, Name => Queue_Access); begin if Object.Queue /= null then Object.Queue.Finalize; Free (Object.Queue); end if; end Finalize; end AWA.Events.Queues;
Fix creation of event queue
Fix creation of event queue
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
af19bc9aa65bacc0cf1350270b682b1b3e2bb335
regtests/security-testsuite.adb
regtests/security-testsuite.adb
----------------------------------------------------------------------- -- Security testsuite - Ada Security Test suite -- 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 Security.Openid.Tests; with Security.Permissions.Tests; with Security.Policies.Tests; package body Security.Testsuite is 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 Security.Openid.Tests.Add_Tests (Ret); Security.Permissions.Tests.Add_Tests (Ret); Security.Policies.Tests.Add_Tests (Ret); return Ret; end Suite; end Security.Testsuite;
----------------------------------------------------------------------- -- Security testsuite - Ada Security Test suite -- 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 Security.OpenID.Tests; with Security.Permissions.Tests; with Security.Policies.Tests; package body Security.Testsuite is 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 Security.OpenID.Tests.Add_Tests (Ret); Security.Permissions.Tests.Add_Tests (Ret); Security.Policies.Tests.Add_Tests (Ret); return Ret; end Suite; end Security.Testsuite;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-security
bdf7f8b5af19ca9b0e760dadcaff05be4fca0843
src/sys/streams/util-streams-aes.ads
src/sys/streams/util-streams-aes.ads
----------------------------------------------------------------------- -- util-streams-aes -- AES encoding and decoding streams -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.AES; with Util.Streams.Buffered.Encoders; -- == AES Encoding Streams == -- The `Util.Streams.AES` package define the `Encoding_Stream` and `Decoding_Stream` types to -- encrypt and decrypt using the AES cipher. Before using these streams, you must use -- the `Set_Key` procedure to setup the encryption or decryption key and define the AES -- encryption mode to be used. The following encryption modes are supported: -- -- * AES-ECB -- * AES-CBC -- * AES-PCBC -- * AES-CFB -- * AES-OFB -- * AES-CTR -- -- The encryption and decryption keys are represented by the `Util.Encoders.Secret_Key` limited -- type. The key cannot be copied, has its content protected and will erase the memory once -- the instance is deleted. The size of the encryption key defines the AES encryption level -- to be used: -- -- * Use 16 bytes, or `Util.Encoders.AES.AES_128_Length` for AES-128, -- * Use 24 bytes, or `Util.Encoders.AES.AES_192_Length` for AES-192, -- * Use 32 bytes, or `Util.Encoders.AES.AES_256_Length` for AES-256. -- -- Other key sizes will raise a pre-condition or constraint error exception. -- The recommended key size is 32 bytes to use AES-256. The key could be declared as follows: -- -- Key : Util.Encoders.Secret_Key -- (Length => Util.Encoders.AES.AES_256_Length); -- -- The encryption and decryption key are initialized by using the `Util.Encoders.Create` -- operations or by using one of the key derivative functions provided by the -- `Util.Encoders.KDF` package. A simple string password is created by using: -- -- Password_Key : constant Util.Encoders.Secret_Key -- := Util.Encoders.Create ("mysecret"); -- -- Using a password key like this is not the good practice and it may be useful to generate -- a stronger key by using one of the key derivative function. We will use the -- PBKDF2 HMAC-SHA256 with 20000 loops (see RFC 8018): -- -- Util.Encoders.KDF.PBKDF2_HMAC_SHA256 (Password => Password_Key, -- Salt => Password_Key, -- Counter => 20000, -- Result => Key); -- -- To write a text, encrypt the content and save the file, we can chain several stream objects -- together. Because they are chained, the last stream object in the chain must be declared -- first and the first element of the chain will be declared last. The following declaration -- is used: -- -- Out_Stream : aliased Util.Streams.Files.File_Stream; -- Cipher : aliased Util.Streams.AES.Encoding_Stream; -- Printer : Util.Streams.Texts.Print_Stream; -- -- The stream objects are chained together by using their `Initialize` procedure. -- The `Out_Stream` is configured to write on the `encrypted.aes` file. -- The `Cipher` is configured to write in the `Out_Stream` with a 32Kb buffer. -- The `Printer` is configured to write in the `Cipher` with a 4Kb buffer. -- -- Out_Stream.Initialize (Mode => Ada.Streams.Stream_IO.In_File, -- Name => "encrypted.aes"); -- Cipher.Initialize (Output => Out_Stream'Access, -- Size => 32768); -- Printer.Initialize (Output => Cipher'Access, -- Size => 4096); -- -- The last step before using the cipher is to configure the encryption key and modes: -- -- Cipher.Set_Key (Secret => Key, Mode => Util.Encoders.AES.ECB); -- -- It is now possible to write the text by using the `Printer` object: -- -- Printer.Write ("Hello world!"); -- -- package Util.Streams.AES is package Encoding is new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Encoder); package Decoding is new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Decoder); type Encoding_Stream is new Encoding.Encoder_Stream with null record; -- Set the encryption key and mode to be used. procedure Set_Key (Stream : in out Encoding_Stream; Secret : in Util.Encoders.Secret_Key; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC); -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (Stream : in out Encoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type); type Decoding_Stream is new Decoding.Encoder_Stream with null record; -- Set the encryption key and mode to be used. procedure Set_Key (Stream : in out Decoding_Stream; Secret : in Util.Encoders.Secret_Key; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC); -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (Stream : in out Decoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type); end Util.Streams.AES;
----------------------------------------------------------------------- -- util-streams-aes -- AES encoding and decoding streams -- Copyright (C) 2019, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.AES; with Util.Streams.Buffered.Encoders; -- == AES Encoding Streams == -- The `Util.Streams.AES` package define the `Encoding_Stream` and `Decoding_Stream` types to -- encrypt and decrypt using the AES cipher. Before using these streams, you must use -- the `Set_Key` procedure to setup the encryption or decryption key and define the AES -- encryption mode to be used. The following encryption modes are supported: -- -- * AES-ECB -- * AES-CBC -- * AES-PCBC -- * AES-CFB -- * AES-OFB -- * AES-CTR -- -- The encryption and decryption keys are represented by the `Util.Encoders.Secret_Key` limited -- type. The key cannot be copied, has its content protected and will erase the memory once -- the instance is deleted. The size of the encryption key defines the AES encryption level -- to be used: -- -- * Use 16 bytes, or `Util.Encoders.AES.AES_128_Length` for AES-128, -- * Use 24 bytes, or `Util.Encoders.AES.AES_192_Length` for AES-192, -- * Use 32 bytes, or `Util.Encoders.AES.AES_256_Length` for AES-256. -- -- Other key sizes will raise a pre-condition or constraint error exception. -- The recommended key size is 32 bytes to use AES-256. The key could be declared as follows: -- -- Key : Util.Encoders.Secret_Key -- (Length => Util.Encoders.AES.AES_256_Length); -- -- The encryption and decryption key are initialized by using the `Util.Encoders.Create` -- operations or by using one of the key derivative functions provided by the -- `Util.Encoders.KDF` package. A simple string password is created by using: -- -- Password_Key : constant Util.Encoders.Secret_Key -- := Util.Encoders.Create ("mysecret"); -- -- Using a password key like this is not the good practice and it may be useful to generate -- a stronger key by using one of the key derivative function. We will use the -- PBKDF2 HMAC-SHA256 with 20000 loops (see RFC 8018): -- -- Util.Encoders.KDF.PBKDF2_HMAC_SHA256 (Password => Password_Key, -- Salt => Password_Key, -- Counter => 20000, -- Result => Key); -- -- To write a text, encrypt the content and save the file, we can chain several stream objects -- together. Because they are chained, the last stream object in the chain must be declared -- first and the first element of the chain will be declared last. The following declaration -- is used: -- -- Out_Stream : aliased Util.Streams.Files.File_Stream; -- Cipher : aliased Util.Streams.AES.Encoding_Stream; -- Printer : Util.Streams.Texts.Print_Stream; -- -- The stream objects are chained together by using their `Initialize` procedure. -- The `Out_Stream` is configured to write on the `encrypted.aes` file. -- The `Cipher` is configured to write in the `Out_Stream` with a 32Kb buffer. -- The `Printer` is configured to write in the `Cipher` with a 4Kb buffer. -- -- Out_Stream.Initialize (Mode => Ada.Streams.Stream_IO.In_File, -- Name => "encrypted.aes"); -- Cipher.Initialize (Output => Out_Stream'Unchecked_Access, -- Size => 32768); -- Printer.Initialize (Output => Cipher'Unchecked_Access, -- Size => 4096); -- -- The last step before using the cipher is to configure the encryption key and modes: -- -- Cipher.Set_Key (Secret => Key, Mode => Util.Encoders.AES.ECB); -- -- It is now possible to write the text by using the `Printer` object: -- -- Printer.Write ("Hello world!"); -- -- package Util.Streams.AES is package Encoding is new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Encoder); package Decoding is new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Decoder); type Encoding_Stream is new Encoding.Encoder_Stream with null record; -- Set the encryption key and mode to be used. procedure Set_Key (Stream : in out Encoding_Stream; Secret : in Util.Encoders.Secret_Key; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC); -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (Stream : in out Encoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type); type Decoding_Stream is new Decoding.Encoder_Stream with null record; -- Set the encryption key and mode to be used. procedure Set_Key (Stream : in out Decoding_Stream; Secret : in Util.Encoders.Secret_Key; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC); -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (Stream : in out Decoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type); end Util.Streams.AES;
Fix documentation example
Fix documentation example
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ebd0a12bcb8f85da91cc66f5cb63af93c5d7440d
src/security.ads
src/security.ads
----------------------------------------------------------------------- -- security -- Security -- 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. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- The security framework uses the following abstractions: -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- == Overview == -- An application will create a security policy manager and register one or several security -- policies. The framework defines a simple role based security policy and an URL security -- policy intended to provide security in web applications. The security policy manager reads -- some security policy configuration file which allows the security policies to configure -- and create the security controllers. These controllers will enforce the security according -- to the application security rules. All these components (yellow) are built only once when -- an application starts. -- -- A user is authenticated through an authentication system which creates a <tt>Principal</tt> -- instance that identifies the user (green). The security framework provides two authentication -- systems: OpenID and OAuth. -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- When a permission must be enforced, a security context is created and linked to the -- <tt>Principal</tt> instance. Additional security policy context can be added depending on -- the application context. To check the permission, the security policy manager is called -- and it will ask a security controller to verify the permission. -- -- @include security-permissions.ads -- @include security-openid.ads -- @include security-oauth.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
----------------------------------------------------------------------- -- security -- Security -- 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. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- The security framework uses the following abstractions: -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- == Overview == -- An application will create a security policy manager and register one or several security -- policies. The framework defines a simple role based security policy and an URL security -- policy intended to provide security in web applications. The security policy manager reads -- some security policy configuration file which allows the security policies to configure -- and create the security controllers. These controllers will enforce the security according -- to the application security rules. All these components (yellow) are built only once when -- an application starts. -- -- A user is authenticated through an authentication system which creates a <tt>Principal</tt> -- instance that identifies the user (green). The security framework provides two authentication -- systems: OpenID and OAuth. -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- When a permission must be enforced, a security context is created and linked to the -- <tt>Principal</tt> instance. Additional security policy context can be added depending on -- the application context. To check the permission, the security policy manager is called -- and it will ask a security controller to verify the permission. -- -- The framework allows an application to plug its own security policy, its own policy context, -- its own principal and authentication mechanism. -- -- @include security-permissions.ads -- @include security-openid.ads -- @include security-oauth.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-security
d86a47fdc0c78b85d79cd6da45ea11d60988519e
awa/plugins/awa-storages/src/awa-storages-beans.adb
awa/plugins/awa-storages/src/awa-storages-beans.adb
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with ADO; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Helpers.Requests; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" then Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value)); elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Bean); begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (0).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with ADO; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Helpers.Requests; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" then Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value)); elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Bean); begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (0).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
Implement the Load procedure to get the folders and files
Implement the Load procedure to get the folders and files
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
fd25bf8b1626e260e5e5f0071c6fe41d41d56329
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; Memory.Frames := Frames.Create_Root; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; end MAT.Memory.Targets;
Create the frame object by using Create_Frame_Root
Create the frame object by using Create_Frame_Root
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
2d44357dc140056518617c161e79bd64032f3e17
src/util-beans-basic-lists.adb
src/util-beans-basic-lists.adb
----------------------------------------------------------------------- -- Util.Beans.Basic.Lists -- List bean given access to a vector -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Beans.Basic.Lists is -- ------------------------------ -- Initialize the list bean. -- ------------------------------ overriding procedure Initialize (Object : in out List_Bean) is Bean : constant Readonly_Bean_Access := Object.Current'Unchecked_Access; begin Object.Row := Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ function Get_Count (From : in List_Bean) return Natural is begin return Natural (Vectors.Length (From.List)); end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ procedure Set_Row_Index (From : in out List_Bean; Index : in Natural) is begin From.Current := Vectors.Element (From.List, Index - 1); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object is begin return From.Row; end Get_Row; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : in List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (Integer (From.List.Length)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Deletes the list bean -- ------------------------------ procedure Free (List : in out Util.Beans.Basic.Readonly_Bean_Access) is procedure Free is new Ada.Unchecked_Deallocation (List_Bean'Class, List_Bean_Access); begin if List.all in List_Bean'Class then declare L : List_Bean_Access := List_Bean (List.all)'Unchecked_Access; begin Free (L); List := null; end; end if; end Free; end Util.Beans.Basic.Lists;
----------------------------------------------------------------------- -- Util.Beans.Basic.Lists -- List bean given access to a vector -- Copyright (C) 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Beans.Basic.Lists is -- ------------------------------ -- Initialize the list bean. -- ------------------------------ overriding procedure Initialize (Object : in out List_Bean) is Bean : constant Readonly_Bean_Access := Object.Current'Unchecked_Access; begin Object.Row := Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ function Get_Count (From : in List_Bean) return Natural is begin return Natural (Vectors.Length (From.List)); end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ procedure Set_Row_Index (From : in out List_Bean; Index : in Natural) is begin From.Current_Index := Index; From.Current := Vectors.Element (From.List, Index - 1); end Set_Row_Index; -- ------------------------------ -- Returns the current row index. -- ------------------------------ function Get_Row_Index (From : in List_Bean) return Natural is begin return From.Current_Index; end Get_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object is begin return From.Row; end Get_Row; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : in List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (Integer (From.List.Length)); elsif Name = "rowIndex" then return Util.Beans.Objects.To_Object (From.Current_Index); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Deletes the list bean -- ------------------------------ procedure Free (List : in out Util.Beans.Basic.Readonly_Bean_Access) is procedure Free is new Ada.Unchecked_Deallocation (List_Bean'Class, List_Bean_Access); begin if List.all in List_Bean'Class then declare L : List_Bean_Access := List_Bean (List.all)'Unchecked_Access; begin Free (L); List := null; end; end if; end Free; end Util.Beans.Basic.Lists;
Implement the Get_Row_Index Recognize 'rowIndex' as a name for the list bean to return the current row index
Implement the Get_Row_Index Recognize 'rowIndex' as a name for the list bean to return the current row index
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f00c97324f1b6ea8f4e44dadcbdba2745960e401
src/el-expressions-nodes.ads
src/el-expressions-nodes.ads
----------------------------------------------------------------------- -- EL.Expressions -- Expression Nodes -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The 'ELNode' describes an expression that can later be evaluated -- on an expression context. Expressions are parsed and translated -- to a read-only tree. with EL.Functions; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; private package EL.Expressions.Nodes is pragma Preelaborate; use EL.Functions; use Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Unbounded; type Reduction; type ELNode is abstract tagged limited record Ref_Counter : Util.Concurrent.Counters.Counter; end record; type ELNode_Access is access all ELNode'Class; type Reduction is record Node : ELNode_Access; Value : EL.Objects.Object; end record; -- Evaluate a node on a given context. If function Get_Safe_Value (Expr : in ELNode; Context : in ELContext'Class) return Object; -- Evaluate a node on a given context. function Get_Value (Expr : in ELNode; Context : in ELContext'Class) return Object is abstract; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. function Reduce (Expr : access ELNode; Context : in ELContext'Class) return Reduction is abstract; -- Delete the expression tree (calls Delete (ELNode_Access) recursively). procedure Delete (Node : in out ELNode) is abstract; -- Delete the expression tree. Free the memory allocated by nodes -- of the expression tree. Clears the node pointer. procedure Delete (Node : in out ELNode_Access); -- ------------------------------ -- Unary expression node -- ------------------------------ type ELUnary is new ELNode with private; type Unary_Node is (EL_VOID, EL_NOT, EL_MINUS, EL_EMPTY); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELUnary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELUnary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELUnary); -- ------------------------------ -- Binary expression node -- ------------------------------ type ELBinary is new ELNode with private; type Binary_Node is (EL_EQ, EL_NE, EL_LE, EL_LT, EL_GE, EL_GT, EL_ADD, EL_SUB, EL_MUL, EL_DIV, EL_MOD, EL_AND, EL_OR, EL_LAND, EL_LOR, EL_CONCAT); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELBinary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELBinary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELBinary); -- ------------------------------ -- Ternary expression node -- ------------------------------ type ELTernary is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELTernary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELTernary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELTernary); -- ------------------------------ -- Variable to be looked at in the expression context -- ------------------------------ type ELVariable is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELVariable; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELVariable; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELVariable); -- ------------------------------ -- Value property referring to a variable -- ------------------------------ type ELValue (Len : Natural) is new ELNode with private; type ELValue_Access is access all ELValue'Class; -- Check if the target bean is a readonly bean. function Is_Readonly (Node : in ELValue; Context : in ELContext'Class) return Boolean; -- Evaluate the node and return a method info with -- the bean object and the method binding. function Get_Method_Info (Node : in ELValue; Context : in ELContext'Class) return Method_Info; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELValue; Context : ELContext'Class) return Object; -- Evaluate the node and set the value on the associated bean. -- Raises Invalid_Variable if the target object is not a bean. -- Raises Invalid_Expression if the target bean is not writeable. procedure Set_Value (Node : in ELValue; Context : in ELContext'Class; Value : in Objects.Object); -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELValue; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELValue); -- ------------------------------ -- Literal object (integer, boolean, float, string) -- ------------------------------ type ELObject is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELObject; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELObject; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELObject); -- ------------------------------ -- Function call with up to 4 arguments -- ------------------------------ type ELFunction is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELFunction; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELFunction; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELFunction); -- Create constant nodes function Create_Node (Value : Boolean) return ELNode_Access; function Create_Node (Value : Long_Long_Integer) return ELNode_Access; function Create_Node (Value : String) return ELNode_Access; function Create_Node (Value : Wide_Wide_String) return ELNode_Access; function Create_Node (Value : Long_Float) return ELNode_Access; function Create_Node (Value : Unbounded_Wide_Wide_String) return ELNode_Access; function Create_Variable (Name : in Wide_Wide_String) return ELNode_Access; function Create_Value (Variable : in ELNode_Access; Name : in Wide_Wide_String) return ELNode_Access; -- Create unary expressions function Create_Node (Of_Type : Unary_Node; Expr : ELNode_Access) return ELNode_Access; -- Create binary expressions function Create_Node (Of_Type : Binary_Node; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a ternary expression. function Create_Node (Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access) return ELNode_Access; private type ELUnary is new ELNode with record Kind : Unary_Node; Node : ELNode_Access; end record; -- ------------------------------ -- Binary nodes -- ------------------------------ type ELBinary is new ELNode with record Kind : Binary_Node; Left : ELNode_Access; Right : ELNode_Access; end record; -- ------------------------------ -- Ternary expression -- ------------------------------ type ELTernary is new ELNode with record Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access; end record; -- #{bean.name} - Bean name, Bean property -- #{bean[12]} - Bean name, -- Variable to be looked at in the expression context type ELVariable is new ELNode with record Name : Unbounded_String; end record; type ELVariable_Access is access all ELVariable; type ELValue (Len : Natural) is new ELNode with record Variable : ELNode_Access; Name : String (1 .. Len); end record; -- A literal object (integer, boolean, float, String) type ELObject is new ELNode with record Value : Object; end record; -- A function call with up to 4 arguments. type ELFunction is new ELNode with record Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access; end record; end EL.Expressions.Nodes;
----------------------------------------------------------------------- -- EL.Expressions -- Expression Nodes -- 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. ----------------------------------------------------------------------- -- The 'ELNode' describes an expression that can later be evaluated -- on an expression context. Expressions are parsed and translated -- to a read-only tree. with EL.Functions; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; private package EL.Expressions.Nodes is pragma Preelaborate; use EL.Functions; use Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Unbounded; type Reduction; type ELNode is abstract tagged limited record Ref_Counter : Util.Concurrent.Counters.Counter; end record; type ELNode_Access is access all ELNode'Class; type Reduction is record Node : ELNode_Access; Value : EL.Objects.Object; end record; -- Evaluate a node on a given context. If function Get_Safe_Value (Expr : in ELNode; Context : in ELContext'Class) return Object; -- Evaluate a node on a given context. function Get_Value (Expr : in ELNode; Context : in ELContext'Class) return Object is abstract; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. function Reduce (Expr : access ELNode; Context : in ELContext'Class) return Reduction is abstract; -- Delete the expression tree (calls Delete (ELNode_Access) recursively). procedure Delete (Node : in out ELNode) is abstract; -- Delete the expression tree. Free the memory allocated by nodes -- of the expression tree. Clears the node pointer. procedure Delete (Node : in out ELNode_Access); -- ------------------------------ -- Unary expression node -- ------------------------------ type ELUnary is new ELNode with private; type Unary_Node is (EL_VOID, EL_NOT, EL_MINUS, EL_EMPTY); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELUnary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELUnary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELUnary); -- ------------------------------ -- Binary expression node -- ------------------------------ type ELBinary is new ELNode with private; type Binary_Node is (EL_EQ, EL_NE, EL_LE, EL_LT, EL_GE, EL_GT, EL_ADD, EL_SUB, EL_MUL, EL_DIV, EL_MOD, EL_AND, EL_OR, EL_LAND, EL_LOR, EL_CONCAT); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELBinary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELBinary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELBinary); -- ------------------------------ -- Ternary expression node -- ------------------------------ type ELTernary is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELTernary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELTernary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELTernary); -- ------------------------------ -- Variable to be looked at in the expression context -- ------------------------------ type ELVariable is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELVariable; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELVariable; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELVariable); -- ------------------------------ -- Value property referring to a variable -- ------------------------------ type ELValue (Len : Natural) is new ELNode with private; type ELValue_Access is access all ELValue'Class; -- Check if the target bean is a readonly bean. function Is_Readonly (Node : in ELValue; Context : in ELContext'Class) return Boolean; -- Get the variable name. function Get_Variable_Name (Node : in ELValue) return String; -- Evaluate the node and return a method info with -- the bean object and the method binding. function Get_Method_Info (Node : in ELValue; Context : in ELContext'Class) return Method_Info; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELValue; Context : ELContext'Class) return Object; -- Evaluate the node and set the value on the associated bean. -- Raises Invalid_Variable if the target object is not a bean. -- Raises Invalid_Expression if the target bean is not writeable. procedure Set_Value (Node : in ELValue; Context : in ELContext'Class; Value : in Objects.Object); -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELValue; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELValue); -- ------------------------------ -- Literal object (integer, boolean, float, string) -- ------------------------------ type ELObject is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELObject; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELObject; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELObject); -- ------------------------------ -- Function call with up to 4 arguments -- ------------------------------ type ELFunction is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELFunction; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELFunction; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELFunction); -- Create constant nodes function Create_Node (Value : Boolean) return ELNode_Access; function Create_Node (Value : Long_Long_Integer) return ELNode_Access; function Create_Node (Value : String) return ELNode_Access; function Create_Node (Value : Wide_Wide_String) return ELNode_Access; function Create_Node (Value : Long_Float) return ELNode_Access; function Create_Node (Value : Unbounded_Wide_Wide_String) return ELNode_Access; function Create_Variable (Name : in Wide_Wide_String) return ELNode_Access; function Create_Value (Variable : in ELNode_Access; Name : in Wide_Wide_String) return ELNode_Access; -- Create unary expressions function Create_Node (Of_Type : Unary_Node; Expr : ELNode_Access) return ELNode_Access; -- Create binary expressions function Create_Node (Of_Type : Binary_Node; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a ternary expression. function Create_Node (Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access) return ELNode_Access; private type ELUnary is new ELNode with record Kind : Unary_Node; Node : ELNode_Access; end record; -- ------------------------------ -- Binary nodes -- ------------------------------ type ELBinary is new ELNode with record Kind : Binary_Node; Left : ELNode_Access; Right : ELNode_Access; end record; -- ------------------------------ -- Ternary expression -- ------------------------------ type ELTernary is new ELNode with record Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access; end record; -- #{bean.name} - Bean name, Bean property -- #{bean[12]} - Bean name, -- Variable to be looked at in the expression context type ELVariable is new ELNode with record Name : Unbounded_String; end record; type ELVariable_Access is access all ELVariable; type ELValue (Len : Natural) is new ELNode with record Variable : ELNode_Access; Name : String (1 .. Len); end record; -- A literal object (integer, boolean, float, String) type ELObject is new ELNode with record Value : Object; end record; -- A function call with up to 4 arguments. type ELFunction is new ELNode with record Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access; end record; end EL.Expressions.Nodes;
Declare Get_Variable_Name function
Declare Get_Variable_Name function
Ada
apache-2.0
stcarrez/ada-el
bb5f04bb8b3f08900fa2f97251697cca2ce69a57
src/util-concurrent-pools.ads
src/util-concurrent-pools.ads
----------------------------------------------------------------------- -- Util.Concurrent.Pools -- Concurrent Pools -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; -- The <b>Util.Concurrent.Pools</b> generic defines a pool of objects which -- can be shared by multiple threads. First, the pool is configured to have -- a number of objects by using the <b>Set_Size</b> procedure. Then, a thread -- that needs an object uses the <b>Get_Instance</b> to get an object. -- The object is removed from the pool. As soon as the thread has finished, -- it puts back the object in the pool using the <b>Release</b> procedure. -- -- The <b>Get_Instance</b> entry will block until an object is available. generic type Element_Type is private; package Util.Concurrent.Pools is pragma Preelaborate; FOREVER : constant Duration := -1.0; -- Exception raised if the Get_Instance timeout exceeded. Timeout : exception; -- Pool of objects type Pool is limited new Ada.Finalization.Limited_Controlled with private; -- Get an element instance from the pool. -- Wait until one instance gets available. procedure Get_Instance (From : in out Pool; Item : out Element_Type; Wait : in Duration := FOREVER); -- Put the element back to the pool. procedure Release (Into : in out Pool; Item : in Element_Type); -- Set the pool size. procedure Set_Size (Into : in out Pool; Capacity : in Positive); -- Get the number of available elements in the pool. procedure Get_Available (From : in out Pool; Available : out Natural); -- Release the pool elements. overriding procedure Finalize (Object : in out Pool); private -- To store the pool elements, we use an array which is allocated dynamically -- by the <b>Set_Size</b> protected operation. The generated code is smaller -- compared to the use of Ada vectors container. type Element_Array is array (Positive range <>) of Element_Type; type Element_Array_Access is access all Element_Array; Null_Element_Array : constant Element_Array_Access := null; -- Pool of objects protected type Protected_Pool is -- Get an element instance from the pool. -- Wait until one instance gets available. entry Get_Instance (Item : out Element_Type); -- Put the element back to the pool. procedure Release (Item : in Element_Type); -- Set the pool size. procedure Set_Size (Capacity : in Natural); -- Get the number of available elements. function Get_Available return Natural; private Available : Natural := 0; Elements : Element_Array_Access := Null_Element_Array; end Protected_Pool; type Pool is limited new Ada.Finalization.Limited_Controlled with record List : Protected_Pool; end record; end Util.Concurrent.Pools;
----------------------------------------------------------------------- -- util-concurrent-pools -- Concurrent Pools -- Copyright (C) 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; -- The <b>Util.Concurrent.Pools</b> generic defines a pool of objects which -- can be shared by multiple threads. First, the pool is configured to have -- a number of objects by using the <b>Set_Size</b> procedure. Then, a thread -- that needs an object uses the <b>Get_Instance</b> to get an object. -- The object is removed from the pool. As soon as the thread has finished, -- it puts back the object in the pool using the <b>Release</b> procedure. -- -- The <b>Get_Instance</b> entry will block until an object is available. generic type Element_Type is private; package Util.Concurrent.Pools is pragma Preelaborate; FOREVER : constant Duration := -1.0; -- Exception raised if the Get_Instance timeout exceeded. Timeout : exception; -- Pool of objects type Pool is limited new Ada.Finalization.Limited_Controlled with private; -- Get an element instance from the pool. -- Wait until one instance gets available. procedure Get_Instance (From : in out Pool; Item : out Element_Type; Wait : in Duration := FOREVER); -- Put the element back to the pool. procedure Release (Into : in out Pool; Item : in Element_Type); -- Set the pool size. procedure Set_Size (Into : in out Pool; Capacity : in Positive); -- Get the number of available elements in the pool. procedure Get_Available (From : in out Pool; Available : out Natural); -- Release the pool elements. overriding procedure Finalize (Object : in out Pool); private -- To store the pool elements, we use an array which is allocated dynamically -- by the <b>Set_Size</b> protected operation. The generated code is smaller -- compared to the use of Ada vectors container. type Element_Array is array (Positive range <>) of Element_Type; type Element_Array_Access is access all Element_Array; Null_Element_Array : constant Element_Array_Access := null; -- Pool of objects protected type Protected_Pool is -- Get an element instance from the pool. -- Wait until one instance gets available. entry Get_Instance (Item : out Element_Type); -- Put the element back to the pool. procedure Release (Item : in Element_Type); -- Set the pool size. procedure Set_Size (Capacity : in Natural); -- Get the number of available elements. function Get_Available return Natural; private Available : Natural := 0; Elements : Element_Array_Access := Null_Element_Array; end Protected_Pool; type Pool is limited new Ada.Finalization.Limited_Controlled with record List : Protected_Pool; end record; end Util.Concurrent.Pools;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bac7475a148a6877a87ea6b216ca1fd0a2978140
src/util-serialize-io-csv.ads
src/util-serialize-io-csv.ads
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- 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 Util.Strings.Vectors; with Util.Streams.Texts; -- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files. -- -- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files package Util.Serialize.IO.CSV is type Row_Type is new Natural; type Column_Type is new Positive; -- ------------------------------ -- CSV Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a CSV output stream. -- The stream object takes care of the CSV escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. procedure Write_Cell (Stream : in out Output_Stream; Value : in String); procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer); procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean); procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new row. procedure New_Row (Stream : in out Output_Stream); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- CSV Parser -- ------------------------------ -- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly -- in Ada records. type Parser is new Serialize.IO.Parser with private; -- Get the header name for the given column. -- If there was no header line, build a default header for the column. function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String; -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type); -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character); -- Get the field separator. function Get_Field_Separator (Handler : in Parser) return Character; -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character); -- Get the comment separator. Returns ASCII.NUL if comments are not supported. function Get_Comment_Separator (Handler : in Parser) return Character; -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True); -- Parse the stream using the CSV parser. overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Get the current location (file and line) to report an error message. overriding function Get_Location (Handler : in Parser) return String; private type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Max_Columns : Column_Type := 1; Column : Column_Type := 1; Row : Row_Type := 0; end record; type Parser is new Util.Serialize.IO.Parser with record Has_Header : Boolean := True; Line_Number : Natural := 1; Row : Row_Type := 0; Headers : Util.Strings.Vectors.Vector; Separator : Character := ','; Comment : Character := ASCII.NUL; Use_Default_Headers : Boolean := False; end record; end Util.Serialize.IO.CSV;
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- 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 Util.Strings.Vectors; with Util.Streams.Texts; -- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files. -- -- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files package Util.Serialize.IO.CSV is type Row_Type is new Natural; type Column_Type is new Positive; -- ------------------------------ -- CSV Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a CSV output stream. -- The stream object takes care of the CSV escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. procedure Write_Cell (Stream : in out Output_Stream; Value : in String); procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer); procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean); procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new row. procedure New_Row (Stream : in out Output_Stream); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- CSV Parser -- ------------------------------ -- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly -- in Ada records. type Parser is new Serialize.IO.Parser with private; -- Get the header name for the given column. -- If there was no header line, build a default header for the column. function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String; -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type); -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character); -- Get the field separator. function Get_Field_Separator (Handler : in Parser) return Character; -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character); -- Get the comment separator. Returns ASCII.NUL if comments are not supported. function Get_Comment_Separator (Handler : in Parser) return Character; -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True); -- Parse the stream using the CSV parser. overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Get the current location (file and line) to report an error message. overriding function Get_Location (Handler : in Parser) return String; private type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Max_Columns : Column_Type := 1; Column : Column_Type := 1; Row : Row_Type := 0; end record; type Parser is new Util.Serialize.IO.Parser with record Has_Header : Boolean := True; Line_Number : Natural := 1; Row : Row_Type := 0; Headers : Util.Strings.Vectors.Vector; Separator : Character := ','; Comment : Character := ASCII.NUL; Use_Default_Headers : Boolean := False; end record; end Util.Serialize.IO.CSV;
Declare the Write_Enum_Entity for enum image value serialization
Declare the Write_Enum_Entity for enum image value serialization
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
edfed549882f73d04309ae93eed0bd1a3f40836f
src/gl/interface/gl-types.ads
src/gl/interface/gl-types.ads
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C.Extensions; with Interfaces.C.Pointers; with GL.Algebra; package GL.Types is pragma Preelaborate; -- These are the types you can and should use with OpenGL functions -- (particularly when dealing with buffer objects). -- Types that are only used internally, but may be needed when interfacing -- with OpenGL-related library APIs can be found in GL.Low_Level. -- Signed integer types type Byte is new C.signed_char; type Short is new C.short; type Int is new C.int; type Long is new C.Extensions.long_long; subtype Size is Int range 0 .. Int'Last; subtype Long_Size is Long range 0 .. Long'Last; -- Unsigned integer types type UByte is new C.unsigned_char; type UShort is new C.unsigned_short; type UInt is new C.unsigned; -- Floating point types ("Single" is used to avoid conflicts with Float) subtype Half is Short; -- F16C extension can be used to convert from/to Single type Single is new C.C_float; type Double is new C.double; subtype Normalized_Single is Single range 0.0 .. 1.0; -- Array types type UByte_Array is array (Size range <>) of aliased UByte; type UShort_Array is array (Size range <>) of aliased UShort; type Int_Array is array (Size range <>) of aliased Int; type UInt_Array is array (Size range <>) of aliased UInt; type Half_Array is array (Size range <>) of aliased Half; type Single_Array is array (Size range <>) of aliased Single; type Double_Array is array (Size range <>) of aliased Double; pragma Convention (C, UByte_Array); pragma Convention (C, UShort_Array); pragma Convention (C, Int_Array); pragma Convention (C, UInt_Array); pragma Convention (C, Half_Array); pragma Convention (C, Single_Array); pragma Convention (C, Double_Array); type Size_Array is array (Size range <>) of aliased Size with Convention => C; -- Type descriptors type Numeric_Type is (Byte_Type, UByte_Type, Short_Type, UShort_Type, Int_Type, UInt_Type, Single_Type, Double_Type, Half_Type); type Signed_Numeric_Type is (Byte_Type, Short_Type, Int_Type, Single_Type, Double_Type, Half_Type); type Unsigned_Numeric_Type is (UByte_Type, UShort_Type, UInt_Type); -- Doesn't really fit here, but there's no other place it fits better type Connection_Mode is (Points, Lines, Line_Loop, Line_Strip, Triangles, Triangle_Strip, Triangle_Fan, Lines_Adjacency, Line_Strip_Adjacency, Triangles_Adjacency, Triangle_Strip_Adjacency, Patches); type Compare_Function is (Never, Less, Equal, LEqual, Greater, Not_Equal, GEqual, Always); subtype Component_Count is Int range 1 .. 4; -- Counts the number of components for vertex attributes subtype Byte_Count is Int range 1 .. 4 with Static_Predicate => Byte_Count in 1 | 2 | 4; -- Number of bytes of a component package Bytes is new GL.Algebra (Element_Type => Byte, Index_Type => Size, Null_Value => 0, One_Value => 1); package Shorts is new GL.Algebra (Element_Type => Short, Index_Type => Size, Null_Value => 0, One_Value => 1); package Ints is new GL.Algebra (Element_Type => Int, Index_Type => Size, Null_Value => 0, One_Value => 1); package Longs is new GL.Algebra (Element_Type => Long, Index_Type => Size, Null_Value => 0, One_Value => 1); package UBytes is new GL.Algebra (Element_Type => UByte, Index_Type => Size, Null_Value => 0, One_Value => 1); package UShorts is new GL.Algebra (Element_Type => UShort, Index_Type => Size, Null_Value => 0, One_Value => 1); package UInts is new GL.Algebra (Element_Type => UInt, Index_Type => Size, Null_Value => 0, One_Value => 1); package Singles is new GL.Algebra (Element_Type => Single, Index_Type => Size, Null_Value => 0.0, One_Value => 1.0); package Doubles is new GL.Algebra (Element_Type => Double, Index_Type => Size, Null_Value => 0.0, One_Value => 1.0); -- Pointer types (for use with data transfer functions package Int_Pointers is new Interfaces.C.Pointers (Size, Int, Int_Array, Int'Last); package UInt_Pointers is new Interfaces.C.Pointers (Size, UInt, UInt_Array, UInt'Last); package Half_Pointers is new Interfaces.C.Pointers (Size, Half, Half_Array, 0); package Single_Pointers is new Interfaces.C.Pointers (Size, Single, Single_Array, 0.0); package Double_Pointers is new Interfaces.C.Pointers (Size, Double, Double_Array, 0.0); type String_Access is not null access constant String; type String_Array is array (Positive range <>) of String_Access; private for Numeric_Type use (Byte_Type => 16#1400#, UByte_Type => 16#1401#, Short_Type => 16#1402#, UShort_Type => 16#1403#, Int_Type => 16#1404#, UInt_Type => 16#1405#, Single_Type => 16#1406#, Double_Type => 16#140A#, Half_Type => 16#140B#); for Numeric_Type'Size use UInt'Size; for Signed_Numeric_Type use (Byte_Type => 16#1400#, Short_Type => 16#1402#, Int_Type => 16#1404#, Single_Type => 16#1406#, Double_Type => 16#140A#, Half_Type => 16#140B#); for Signed_Numeric_Type'Size use UInt'Size; for Unsigned_Numeric_Type use (UByte_Type => 16#1401#, UShort_Type => 16#1403#, UInt_Type => 16#1405#); for Unsigned_Numeric_Type'Size use UInt'Size; for Connection_Mode use (Points => 16#0000#, Lines => 16#0001#, Line_Loop => 16#0002#, Line_Strip => 16#0003#, Triangles => 16#0004#, Triangle_Strip => 16#0005#, Triangle_Fan => 16#0006#, Lines_Adjacency => 16#000A#, Line_Strip_Adjacency => 16#000B#, Triangles_Adjacency => 16#000C#, Triangle_Strip_Adjacency => 16#000D#, Patches => 16#000E#); for Connection_Mode'Size use UInt'Size; for Compare_Function use (Never => 16#0200#, Less => 16#0201#, Equal => 16#0202#, LEqual => 16#0203#, Greater => 16#0204#, Not_Equal => 16#0205#, GEqual => 16#0206#, Always => 16#0207#); for Compare_Function'Size use UInt'Size; end GL.Types;
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C.Extensions; with Interfaces.C.Pointers; with GL.Algebra; package GL.Types is pragma Preelaborate; -- These are the types you can and should use with OpenGL functions -- (particularly when dealing with buffer objects). -- Types that are only used internally, but may be needed when interfacing -- with OpenGL-related library APIs can be found in GL.Low_Level. -- Signed integer types type Byte is new C.signed_char; type Short is new C.short; type Int is new C.int; type Long is new C.Extensions.long_long; subtype Size is Int range 0 .. Int'Last; subtype Long_Size is Long range 0 .. Long'Last; -- Unsigned integer types type UByte is new C.unsigned_char; type UShort is new C.unsigned_short; type UInt is new C.unsigned; -- Floating point types ("Single" is used to avoid conflicts with Float) subtype Half is Short; -- F16C extension can be used to convert from/to Single type Single is new C.C_float; type Double is new C.double; subtype Normalized_Single is Single range 0.0 .. 1.0; -- Array types type UByte_Array is array (Size range <>) of aliased UByte; type UShort_Array is array (Size range <>) of aliased UShort; type Int_Array is array (Size range <>) of aliased Int; type UInt_Array is array (Size range <>) of aliased UInt; type Half_Array is array (Size range <>) of aliased Half; type Single_Array is array (Size range <>) of aliased Single; type Double_Array is array (Size range <>) of aliased Double; pragma Convention (C, UByte_Array); pragma Convention (C, UShort_Array); pragma Convention (C, Int_Array); pragma Convention (C, UInt_Array); pragma Convention (C, Half_Array); pragma Convention (C, Single_Array); pragma Convention (C, Double_Array); type Size_Array is array (Size range <>) of aliased Size with Convention => C; -- Type descriptors type Numeric_Type is (Byte_Type, UByte_Type, Short_Type, UShort_Type, Int_Type, UInt_Type, Single_Type, Double_Type, Half_Type); type Signed_Numeric_Type is (Byte_Type, Short_Type, Int_Type, Single_Type, Double_Type, Half_Type); type Unsigned_Numeric_Type is (UByte_Type, UShort_Type, UInt_Type); -- Doesn't really fit here, but there's no other place it fits better type Connection_Mode is (Points, Lines, Line_Loop, Line_Strip, Triangles, Triangle_Strip, Triangle_Fan, Lines_Adjacency, Line_Strip_Adjacency, Triangles_Adjacency, Triangle_Strip_Adjacency, Patches); type Compare_Function is (Never, Less, Equal, LEqual, Greater, Not_Equal, GEqual, Always); subtype Component_Count is Int range 1 .. 4; -- Counts the number of components for vertex attributes subtype Byte_Count is Int range 1 .. 4 with Static_Predicate => Byte_Count in 1 | 2 | 4; -- Number of bytes of a component package Bytes is new GL.Algebra (Element_Type => Byte, Index_Type => Size, Null_Value => 0, One_Value => 1); package Shorts is new GL.Algebra (Element_Type => Short, Index_Type => Size, Null_Value => 0, One_Value => 1); package Ints is new GL.Algebra (Element_Type => Int, Index_Type => Size, Null_Value => 0, One_Value => 1); package Longs is new GL.Algebra (Element_Type => Long, Index_Type => Size, Null_Value => 0, One_Value => 1); package UBytes is new GL.Algebra (Element_Type => UByte, Index_Type => Size, Null_Value => 0, One_Value => 1); package UShorts is new GL.Algebra (Element_Type => UShort, Index_Type => Size, Null_Value => 0, One_Value => 1); package UInts is new GL.Algebra (Element_Type => UInt, Index_Type => Size, Null_Value => 0, One_Value => 1); package Singles is new GL.Algebra (Element_Type => Single, Index_Type => Size, Null_Value => 0.0, One_Value => 1.0); package Doubles is new GL.Algebra (Element_Type => Double, Index_Type => Size, Null_Value => 0.0, One_Value => 1.0); -- Pointer types (for use with data transfer functions package UByte_Pointers is new Interfaces.C.Pointers (Size, UByte, UByte_Array, UByte'Last); package UShort_Pointers is new Interfaces.C.Pointers (Size, UShort, UShort_Array, UShort'Last); package Int_Pointers is new Interfaces.C.Pointers (Size, Int, Int_Array, Int'Last); package UInt_Pointers is new Interfaces.C.Pointers (Size, UInt, UInt_Array, UInt'Last); package Half_Pointers is new Interfaces.C.Pointers (Size, Half, Half_Array, 0); package Single_Pointers is new Interfaces.C.Pointers (Size, Single, Single_Array, 0.0); package Double_Pointers is new Interfaces.C.Pointers (Size, Double, Double_Array, 0.0); type String_Access is not null access constant String; type String_Array is array (Positive range <>) of String_Access; private for Numeric_Type use (Byte_Type => 16#1400#, UByte_Type => 16#1401#, Short_Type => 16#1402#, UShort_Type => 16#1403#, Int_Type => 16#1404#, UInt_Type => 16#1405#, Single_Type => 16#1406#, Double_Type => 16#140A#, Half_Type => 16#140B#); for Numeric_Type'Size use UInt'Size; for Signed_Numeric_Type use (Byte_Type => 16#1400#, Short_Type => 16#1402#, Int_Type => 16#1404#, Single_Type => 16#1406#, Double_Type => 16#140A#, Half_Type => 16#140B#); for Signed_Numeric_Type'Size use UInt'Size; for Unsigned_Numeric_Type use (UByte_Type => 16#1401#, UShort_Type => 16#1403#, UInt_Type => 16#1405#); for Unsigned_Numeric_Type'Size use UInt'Size; for Connection_Mode use (Points => 16#0000#, Lines => 16#0001#, Line_Loop => 16#0002#, Line_Strip => 16#0003#, Triangles => 16#0004#, Triangle_Strip => 16#0005#, Triangle_Fan => 16#0006#, Lines_Adjacency => 16#000A#, Line_Strip_Adjacency => 16#000B#, Triangles_Adjacency => 16#000C#, Triangle_Strip_Adjacency => 16#000D#, Patches => 16#000E#); for Connection_Mode'Size use UInt'Size; for Compare_Function use (Never => 16#0200#, Less => 16#0201#, Equal => 16#0202#, LEqual => 16#0203#, Greater => 16#0204#, Not_Equal => 16#0205#, GEqual => 16#0206#, Always => 16#0207#); for Compare_Function'Size use UInt'Size; end GL.Types;
Add pointer types for types UByte and UShort
gl: Add pointer types for types UByte and UShort Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
ed73dd7a3ed32d6dcb9a4ae15855152abe7adfd7
src/util-commands-drivers.adb
src/util-commands-drivers.adb
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is use Ada.Strings.Unbounded; -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in Command_Type) is begin null; end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Print (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin Put_Line (" " & Name); end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args); New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command {0}", Cmd_Name); else Target_Cmd.Help (Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Help_Command_Type; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Report the command usage. -- ------------------------------ procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class) is begin Put_Line (To_String (Driver.Desc)); New_Line; Put ("Usage: "); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end Usage; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler) is begin Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Handler => Handler)); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Execute (Name, Args, Context); else Logs.Error ("Unkown command {0}", Name); end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is pragma Unreferenced (Driver); begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is use Ada.Strings.Unbounded; -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in Command_Type) is begin null; end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Print (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin Put_Line (" " & Name); end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args); New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command {0}", Cmd_Name); else Target_Cmd.Help (Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Help_Command_Type; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Report the command usage. -- ------------------------------ procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class) is begin Put_Line (To_String (Driver.Desc)); New_Line; Put ("Usage: "); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end Usage; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler) is begin Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Handler => Handler)); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Execute (Cmd_Args : in Argument_List'Class); Command : constant Command_Access := Driver.Find_Command (Name); procedure Execute (Cmd_Args : in Argument_List'Class) is begin Command.Execute (Name, Cmd_Args, Context); end Execute; begin if Command /= null then declare Config : Config_Type; begin Command.Setup (Config); Config_Parser.Execute (Config, Args, Execute'Access); end; else Logs.Error ("Unkown command {0}", Name); end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is pragma Unreferenced (Driver); begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
Use the Config_Parser to parse the command arguments and then execute the command
Use the Config_Parser to parse the command arguments and then execute the command
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0468ec5923f4f6ba4873a0b42a02d9249ecb7aac
src/util-serialize-io-csv.adb
src/util-serialize-io-csv.adb
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; with Util.Dates.ISO8601; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. -- ------------------------------ procedure Write_Cell (Stream : in out Output_Stream; Value : in String) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; Stream.Write ('"'); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write (Util.Strings.Image (Value)); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; if Value then Stream.Write ("true"); else Stream.Write ("false"); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ("""null"""); when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("""true"""); else Stream.Write ("""false"""); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (","); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; -- ----------------------- -- Write the attribute name/value pair. -- ----------------------- overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Entity; -- ----------------------- -- Write the entity value. -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND)); 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 Stream.Write_Entity (Name, Value); end Write_Enum_Entity; -- ------------------------------ -- Get the header name for the given column. -- If there was no header line, build a default header for the column. -- ------------------------------ function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. -- ------------------------------ procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Parser'Class (Handler).Finish_Object (""); end if; Parser'Class (Handler).Start_Object (""); end if; Handler.Row := Row; Parser'Class (Handler).Set_Member (Name, Util.Beans.Objects.To_Object (Value)); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. -- ------------------------------ procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. -- ------------------------------ procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; Context : Element_Context_Access; begin Context_Stack.Push (Handler.Stack); Context := Context_Stack.Current (Handler.Stack); Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access; if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Context_Stack.Pop (Handler.Stack); return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2015, 2016, 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.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; with Util.Dates.ISO8601; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. -- ------------------------------ procedure Write_Cell (Stream : in out Output_Stream; Value : in String) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; Stream.Write ('"'); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write (Util.Strings.Image (Value)); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; if Value then Stream.Write ("true"); else Stream.Write ("false"); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ("""null"""); when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("""true"""); else Stream.Write ("""false"""); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (","); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; -- ----------------------- -- Write the attribute name/value pair. -- ----------------------- overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; -- ----------------------- -- Write the entity value. -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND)); 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 Stream.Write_Entity (Name, Value); end Write_Enum_Entity; -- ------------------------------ -- Get the header name for the given column. -- If there was no header line, build a default header for the column. -- ------------------------------ function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. -- ------------------------------ procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Parser'Class (Handler).Finish_Object (""); end if; Parser'Class (Handler).Start_Object (""); end if; Handler.Row := Row; Parser'Class (Handler).Set_Member (Name, Util.Beans.Objects.To_Object (Value)); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. -- ------------------------------ procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. -- ------------------------------ procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; Context : Element_Context_Access; begin Context_Stack.Push (Handler.Stack); Context := Context_Stack.Current (Handler.Stack); Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access; if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Context_Stack.Pop (Handler.Stack); return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
Add pragma Unreferenced to unused parameters
Add pragma Unreferenced to unused parameters
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
98097d90f9a97d05893c86d3618a214880457893
samples/asf_volume_server.adb
samples/asf_volume_server.adb
----------------------------------------------------------------------- -- asf_volume_server -- The volume_server application with Ada Server Faces -- 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.IO_Exceptions; with ASF.Server.Web; with ASF.Servlets; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Measures; with ASF.Filters.Dump; with ASF.Beans; with ASF.Applications; with ASF.Applications.Main; with ASF.Applications.Main.Configs; with Util.Beans.Objects; with Util.Log.Loggers; with Countries; with Volume; with Messages; procedure Asf_Volume_Server is CONTEXT_PATH : constant String := "/volume"; CONFIG_PATH : constant String := "samples.properties"; Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid"); Factory : ASF.Applications.Main.Application_Factory; App : aliased ASF.Applications.Main.Application; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Perf : aliased ASF.Servlets.Measures.Measure_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Bean : aliased Volume.Compute_Bean; Conv : aliased Volume.Float_Converter; WS : ASF.Server.Web.AWS_Container; C : ASF.Applications.Config; None : ASF.Beans.Parameter_Bean_Ref.Ref; begin C.Set (ASF.Applications.VIEW_EXT, ".html"); C.Set (ASF.Applications.VIEW_DIR, "samples/web"); C.Set ("web.dir", "samples/web"); begin C.Load_Properties (CONFIG_PATH); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; App.Initialize (C, Factory); App.Set_Global ("contextPath", CONTEXT_PATH); App.Set_Global ("compute", Util.Beans.Objects.To_Object (Bean'Unchecked_Access, Util.Beans.Objects.STATIC)); App.Set_Global ("countries", Util.Beans.Objects.To_Object (Countries.Create_Country_List)); -- Declare a global bean to identify this sample from within the XHTML files. App.Set_Global ("sampleName", "volume"); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access); App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access); App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.png"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.js"); App.Add_Converter (Name => "float", Converter => Conv'Unchecked_Access); App.Register_Class (Name => "Message_Bean", Handler => Messages.Create_Message_Bean'Access); App.Register_Class (Name => "Message_List", Handler => Messages.Create_Message_List'Access); App.Register (Name => "message", Class => "Message_Bean", Params => None); App.Register (Name => "messages", Class => "Message_List", Params => None); ASF.Applications.Main.Configs.Read_Configuration (App, "samples/web/WEB-INF/web.xml"); WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/volume/compute.html"); WS.Start; delay 6000.0; end Asf_Volume_Server;
----------------------------------------------------------------------- -- asf_volume_server -- The volume_server application with Ada Server Faces -- Copyright (C) 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with ASF.Server.Web; with ASF.Servlets; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Measures; with ASF.Filters.Dump; with ASF.Beans; with ASF.Applications; with ASF.Applications.Main; with ASF.Applications.Main.Configs; with Util.Beans.Objects; with Util.Log.Loggers; with Countries; with Volume; with Messages; procedure Asf_Volume_Server is CONTEXT_PATH : constant String := "/volume"; CONFIG_PATH : constant String := "samples.properties"; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid"); Factory : ASF.Applications.Main.Application_Factory; App : aliased ASF.Applications.Main.Application; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Perf : aliased ASF.Servlets.Measures.Measure_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Bean : aliased Volume.Compute_Bean; Conv : aliased Volume.Float_Converter; WS : ASF.Server.Web.AWS_Container; C : ASF.Applications.Config; None : ASF.Beans.Parameter_Bean_Ref.Ref; begin C.Set (ASF.Applications.VIEW_EXT, ".html"); C.Set (ASF.Applications.VIEW_DIR, "samples/web"); C.Set ("web.dir", "samples/web"); begin C.Load_Properties (CONFIG_PATH); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; App.Initialize (C, Factory); App.Set_Global ("contextPath", CONTEXT_PATH); App.Set_Global ("compute", Util.Beans.Objects.To_Object (Bean'Unchecked_Access, Util.Beans.Objects.STATIC)); App.Set_Global ("countries", Util.Beans.Objects.To_Object (Countries.Create_Country_List)); -- Declare a global bean to identify this sample from within the XHTML files. App.Set_Global ("sampleName", "volume"); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access); App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access); App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.png"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.js"); App.Add_Converter (Name => "float", Converter => Conv'Unchecked_Access); App.Register_Class (Name => "Message_Bean", Handler => Messages.Create_Message_Bean'Access); App.Register_Class (Name => "Message_List", Handler => Messages.Create_Message_List'Access); App.Register (Name => "message", Class => "Message_Bean", Params => None); App.Register (Name => "messages", Class => "Message_List", Params => None); ASF.Applications.Main.Configs.Read_Configuration (App, "samples/web/WEB-INF/web.xml"); WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/volume/compute.html"); WS.Start; delay 6000.0; end Asf_Volume_Server;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
18893f658bd0bd170c561b2852b6b5e652fd055b
awa/plugins/awa-counters/src/awa-counters-components.ads
awa/plugins/awa-counters/src/awa-counters-components.ads
----------------------------------------------------------------------- -- awa-counters-components -- Counter UI component -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Factory; with ASF.Contexts.Faces; with ASF.Components.Html; -- == Counter Component == -- package AWA.Counters.Components is type UICounter is new ASF.Components.Html.UIHtmlComponent with private; -- Render the counter component. Starts the DL/DD list and write the input -- component with the possible associated error message. overriding procedure Encode_Begin (UI : in UICounter; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Get the AWA Counter component factory. function Definition return ASF.Factory.Factory_Bindings_Access; private type UICounter is new ASF.Components.Html.UIHtmlComponent with null record; end AWA.Counters.Components;
----------------------------------------------------------------------- -- awa-counters-components -- Counter UI component -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Factory; with ASF.Contexts.Faces; with ASF.Components.Html; -- == Counter Component == -- package AWA.Counters.Components is type UICounter is new ASF.Components.Html.UIHtmlComponent with private; -- Check if the counter value is hidden. function Is_Hidden (UI : in UICounter; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean; -- Render the counter component. Starts the DL/DD list and write the input -- component with the possible associated error message. overriding procedure Encode_Begin (UI : in UICounter; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Get the AWA Counter component factory. function Definition return ASF.Factory.Factory_Bindings_Access; private type UICounter is new ASF.Components.Html.UIHtmlComponent with null record; end AWA.Counters.Components;
Declare the Is_Hidden function
Declare the Is_Hidden function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
87468e181541cfb319f6a7dc96dbbb51c16171fe
regtests/ado-drivers-tests.ads
regtests/ado-drivers-tests.ads
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure. procedure Test_Set_Connection (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Initialize operation. procedure Test_Initialize (T : in out Test); -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure. procedure Test_Set_Connection (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); end ADO.Drivers.Tests;
Declare the Test_Initialize procedure
Declare the Test_Initialize procedure
Ada
apache-2.0
stcarrez/ada-ado
b48b38c875383dd28068031cd014ecd5b5b34170
src/gen-commands-generate.adb
src/gen-commands-generate.adb
----------------------------------------------------------------------- -- gen-commands-generate -- Generate command for dynamo -- Copyright (C) 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Ada.Directories; with Ada.Text_IO; package body Gen.Commands.Generate is use GNAT.Command_Line; use Ada.Directories; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name, Args); File_Count : Natural := 0; begin Generator.Read_Project ("dynamo.xml", True); Gen.Generator.Read_Mappings (Generator); -- Parse the command line for the --package option. loop case Getopt ("p: ? -package:") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-package" then Generator.Enable_Package_Generation (Parameter); end if; when 'p' => Generator.Enable_Package_Generation (Parameter); when others => null; end case; end loop; -- Read the model files. loop declare Model_File : constant String := Get_Argument; begin exit when Model_File'Length = 0; File_Count := File_Count + 1; if Ada.Directories.Exists (Model_File) and then Ada.Directories.Kind (Model_File) = Ada.Directories.Directory then Gen.Generator.Read_Models (Generator, Model_File); else Gen.Generator.Read_Model (Generator, Model_File, False); end if; end; end loop; if File_Count = 0 then Gen.Generator.Read_Models (Generator, "db"); end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); Generator.Save_Project; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in out Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("generate: Generate the Ada files for the database model or queries"); Put_Line ("Usage: generate [--package NAME] [MODEL ...]"); New_Line; Put_Line (" Read the XML/XMI model description (Hibernate mapping, query mapping, ...)"); Put_Line (" and generate the Ada model files that correspond to the mapping."); Put_Line (" The --package option allows to generate only the package with the given name."); Put_Line (" The default is to generate all the packages that are recognized."); end Help; end Gen.Commands.Generate;
----------------------------------------------------------------------- -- gen-commands-generate -- Generate command for dynamo -- Copyright (C) 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Ada.Directories; with Ada.Text_IO; package body Gen.Commands.Generate is use GNAT.Command_Line; use Ada.Directories; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name, Args); File_Count : Natural := 0; begin Generator.Read_Project ("dynamo.xml", True); Gen.Generator.Read_Mappings (Generator); -- Parse the command line for the --package option. loop case Getopt ("p: ? -package:") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-package" then Generator.Enable_Package_Generation (Parameter); end if; when 'p' => Generator.Enable_Package_Generation (Parameter); when others => null; end case; end loop; -- Read the model files. loop declare Model_File : constant String := Get_Argument; begin exit when Model_File'Length = 0; File_Count := File_Count + 1; if Ada.Directories.Exists (Model_File) and then Ada.Directories.Kind (Model_File) = Ada.Directories.Directory then Gen.Generator.Read_Models (Generator, Model_File); else Gen.Generator.Read_Model (Generator, Model_File, False); end if; end; end loop; if File_Count = 0 then Gen.Generator.Read_Models (Generator, "db"); end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); Generator.Save_Project; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in out Command; Name : in String; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name, Generator); use Ada.Text_IO; begin Put_Line ("generate: Generate the Ada files for the database model or queries"); Put_Line ("Usage: generate [--package NAME] [MODEL ...]"); New_Line; Put_Line (" Read the XML/XMI model description (Hibernate mapping, query mapping, ...)"); Put_Line (" and generate the Ada model files that correspond to the mapping."); Put_Line (" The --package option allows to generate only the package with the given name."); Put_Line (" The default is to generate all the packages that are recognized."); end Help; end Gen.Commands.Generate;
Add Name parameter to the Help procedure
Add Name parameter to the Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
580a6b863345436fc1b67db96a32ba96577e8f20
mat/src/mat-expressions.ads
mat/src/mat-expressions.ads
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_CONDITION, N_THREAD); type Inside_Type is (INSIDE_FILE, INSIDE_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean; private type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_CONDITION, N_THREAD); type Inside_Type is (INSIDE_FILE, INSIDE_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean; private type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
Define the Create_Addr operation for memory address slot range checking
Define the Create_Addr operation for memory address slot range checking
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
18fc718440550d25aa57b957a4805782b2ba9cb1
samples/import.adb
samples/import.adb
----------------------------------------------------------------------- -- import -- Import some HTML content and generate Wiki text -- Copyright (C) 2015, 2016, 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.Text_IO; with Ada.Wide_Wide_Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with GNAT.Command_Line; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings.Transforms; with Wiki.Strings; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Render.Wiki; with Wiki.Documents; with Wiki.Parsers; procedure Import is use GNAT.Command_Line; use Ada.Strings.Unbounded; use Ada.Strings.UTF_Encoding; procedure Usage; function Is_Url (Name : in String) return Boolean; procedure Parse_Url (Url : in String); procedure Parse (Content : in String); procedure Print (Item : in Wiki.Strings.WString); Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Count : Natural := 0; Html_Mode : Boolean := True; Wiki_Mode : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; procedure Usage is begin Ada.Text_IO.Put_Line ("Import HTML into a target Wiki format"); Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-H] [-d] [-c] {URL | file}"); Ada.Text_IO.Put_Line (" -t Convert to text only"); Ada.Text_IO.Put_Line (" -m Convert to Markdown"); Ada.Text_IO.Put_Line (" -M Convert to Mediawiki"); Ada.Text_IO.Put_Line (" -H Convert to HTML"); Ada.Text_IO.Put_Line (" -d Convert to Dotclear"); Ada.Text_IO.Put_Line (" -c Convert to Creole"); end Usage; procedure Print (Item : in Wiki.Strings.WString) is begin Ada.Wide_Wide_Text_IO.Put (Item); end Print; procedure Parse (Content : in String) is Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); if Wiki_Mode then declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Engine.Set_Syntax (Wiki.SYNTAX_HTML); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access, Syntax); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; elsif Html_Mode then declare Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; else declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; end if; Ada.Wide_Wide_Text_IO.New_Line; end Parse; procedure Parse_Url (Url : in String) is Command : constant String := "wget -q -O - " & Url; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Pipe.Open (Command); Buffer.Initialize (Pipe'Unchecked_Access, 1024 * 1024); Buffer.Read (Content); Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Ada.Text_IO.Put_Line (Command & " exited with status " & Integer'Image (Pipe.Get_Exit_Status)); else Parse (To_String (Content)); end if; end Parse_Url; function Is_Url (Name : in String) return Boolean is begin if Name'Length <= 9 then return False; else return Name (Name'First .. Name'First + 6) = "http://" or Name (Name'First .. Name'First + 7) = "https://"; end if; end Is_Url; begin loop case Getopt ("m M H d c t f:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; Wiki_Mode := True; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; Wiki_Mode := True; when 'H' => Syntax := Wiki.SYNTAX_HTML; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; Wiki_Mode := True; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; Wiki_Mode := True; when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter); begin Html_Filter.Hide (Wiki.Html_Tag'Value (Value & "_TAG")); exception when Constraint_Error => Ada.Text_IO.Put_Line ("Invalid tag " & Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; if Is_Url (Name) then Parse_Url (Name); else Util.Files.Read_File (Name, Data); Parse (To_String (Data)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Import;
----------------------------------------------------------------------- -- import -- Import some HTML content and generate Wiki text -- Copyright (C) 2015, 2016, 2020, 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.Wide_Wide_Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with GNAT.Command_Line; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings.Transforms; with Wiki.Strings; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Render.Wiki; with Wiki.Documents; with Wiki.Parsers; procedure Import is use GNAT.Command_Line; use Ada.Strings.Unbounded; use Ada.Strings.UTF_Encoding; procedure Usage; function Is_Url (Name : in String) return Boolean; procedure Parse_Url (Url : in String); procedure Parse (Content : in String); procedure Print (Item : in Wiki.Strings.WString); Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Count : Natural := 0; Html_Mode : Boolean := True; Wiki_Mode : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; procedure Usage is begin Ada.Text_IO.Put_Line ("Import HTML into a target Wiki format"); Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-H] [-d] [-c] {URL | file}"); Ada.Text_IO.Put_Line (" -t Convert to text only"); Ada.Text_IO.Put_Line (" -m Convert to Markdown"); Ada.Text_IO.Put_Line (" -M Convert to Mediawiki"); Ada.Text_IO.Put_Line (" -H Convert to HTML"); Ada.Text_IO.Put_Line (" -d Convert to Dotclear"); Ada.Text_IO.Put_Line (" -c Convert to Creole"); end Usage; procedure Print (Item : in Wiki.Strings.WString) is begin Ada.Wide_Wide_Text_IO.Put (Item); end Print; procedure Parse (Content : in String) is Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); if Wiki_Mode then declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Engine.Set_Syntax (Wiki.SYNTAX_HTML); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access, Syntax); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; elsif Html_Mode then declare Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; else declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; end if; Ada.Wide_Wide_Text_IO.New_Line; end Parse; procedure Parse_Url (Url : in String) is Command : constant String := "wget -q -O - " & Url; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Pipe.Open (Command); Buffer.Initialize (Pipe'Unchecked_Access, 1024 * 1024); Buffer.Read (Content); Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Ada.Text_IO.Put_Line (Command & " exited with status " & Integer'Image (Pipe.Get_Exit_Status)); else Parse (To_String (Content)); end if; end Parse_Url; function Is_Url (Name : in String) return Boolean is begin if Name'Length <= 9 then return False; else return Name (Name'First .. Name'First + 6) = "http://" or else Name (Name'First .. Name'First + 7) = "https://"; end if; end Is_Url; begin loop case Getopt ("m M H d c t f:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; Wiki_Mode := True; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; Wiki_Mode := True; when 'H' => Syntax := Wiki.SYNTAX_HTML; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; Wiki_Mode := True; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; Wiki_Mode := True; when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter); begin Html_Filter.Hide (Wiki.Html_Tag'Value (Value & "_TAG")); exception when Constraint_Error => Ada.Text_IO.Put_Line ("Invalid tag " & Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; if Is_Url (Name) then Parse_Url (Name); else Util.Files.Read_File (Name, Data); Parse (To_String (Data)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Import;
Fix style warnings: add missing overriding and update and then/or else conditions
Fix style warnings: add missing overriding and update and then/or else conditions
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
e50b3d790be1abe87130afd12d16bec9e4711312
orka_transforms/src/orka-transforms-simd_quaternions.ads
orka_transforms/src/orka-transforms-simd_quaternions.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Orka.Transforms.SIMD_Vectors; generic with package Vectors is new Orka.Transforms.SIMD_Vectors (<>); package Orka.Transforms.SIMD_Quaternions is pragma Pure; type Quaternion is new Vectors.Vector_Type; subtype Vector4 is Vectors.Vector_Type; type Axis_Angle is record Axis : Vectors.Direction; Angle : Vectors.Element_Type; end record; Zero_Rotation : constant Quaternion := (0.0, 0.0, 0.0, 1.0); function "+" (Left, Right : Quaternion) return Quaternion; function "*" (Left, Right : Quaternion) return Quaternion; function "*" (Left : Vectors.Element_Type; Right : Quaternion) return Quaternion; function "*" (Left : Quaternion; Right : Vectors.Element_Type) return Quaternion; function Conjugate (Elements : Quaternion) return Quaternion; function Inverse (Elements : Quaternion) return Quaternion; function Norm (Elements : Quaternion) return Vectors.Element_Type; function Normalize (Elements : Quaternion) return Quaternion; function Normalized (Elements : Quaternion) return Boolean; function To_Axis_Angle (Elements : Quaternion) return Axis_Angle; function From_Axis_Angle (Value : Axis_Angle) return Quaternion; function R (Axis : Vector4; Angle : Vectors.Element_Type) return Quaternion with Pre => Vectors.Normalized (Axis), Post => Normalized (R'Result); -- Return a quaternion that will cause a rotation of Angle radians -- about the given Axis function R (Left, Right : Vector4) return Quaternion with Post => Normalized (R'Result); -- Return the rotation from direction Left to Right function Difference (Left, Right : Quaternion) return Quaternion with Post => Normalized (Difference'Result); -- Return a quaternion describing the rotation from quaternion Left -- to Right (Right is a composite rotation of Left and the result) procedure Rotate_At_Origin (Vector : in out Vector4; Elements : Quaternion) with Pre => Normalized (Elements); function Lerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion with Pre => Time in 0.0 .. 1.0, Post => Normalized (Lerp'Result); -- Return the interpolated normalized quaternion on the chord -- between the Left and Right quaternions. function Slerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion with Pre => Time in 0.0 .. 1.0, Post => Normalized (Slerp'Result); -- Return the interpolated unit quaternion on the shortest arc -- between the Left and Right quaternions. end Orka.Transforms.SIMD_Quaternions;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Orka.Transforms.SIMD_Vectors; generic with package Vectors is new Orka.Transforms.SIMD_Vectors (<>); package Orka.Transforms.SIMD_Quaternions is pragma Pure; type Quaternion is new Vectors.Vector_Type; subtype Vector4 is Vectors.Vector_Type; type Axis_Angle is record Axis : Vectors.Direction; Angle : Vectors.Element_Type; end record; Identity : constant Quaternion := (0.0, 0.0, 0.0, 1.0); function "+" (Left, Right : Quaternion) return Quaternion; function "*" (Left, Right : Quaternion) return Quaternion; function "*" (Left : Vectors.Element_Type; Right : Quaternion) return Quaternion; function "*" (Left : Quaternion; Right : Vectors.Element_Type) return Quaternion; function Conjugate (Elements : Quaternion) return Quaternion; function Inverse (Elements : Quaternion) return Quaternion; function Norm (Elements : Quaternion) return Vectors.Element_Type; function Normalize (Elements : Quaternion) return Quaternion; function Normalized (Elements : Quaternion) return Boolean; function To_Axis_Angle (Elements : Quaternion) return Axis_Angle; function From_Axis_Angle (Value : Axis_Angle) return Quaternion; function R (Axis : Vector4; Angle : Vectors.Element_Type) return Quaternion with Pre => Vectors.Normalized (Axis), Post => Normalized (R'Result); -- Return a quaternion that will cause a rotation of Angle radians -- about the given Axis function R (Left, Right : Vector4) return Quaternion with Post => Normalized (R'Result); -- Return the rotation from direction Left to Right function Difference (Left, Right : Quaternion) return Quaternion with Post => Normalized (Difference'Result); -- Return a quaternion describing the rotation from quaternion Left -- to Right (Right is a composite rotation of Left and the result) procedure Rotate_At_Origin (Vector : in out Vector4; Elements : Quaternion) with Pre => Normalized (Elements); function Lerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion with Pre => Time in 0.0 .. 1.0, Post => Normalized (Lerp'Result); -- Return the interpolated normalized quaternion on the chord -- between the Left and Right quaternions. function Slerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion with Pre => Time in 0.0 .. 1.0, Post => Normalized (Slerp'Result); -- Return the interpolated unit quaternion on the shortest arc -- between the Left and Right quaternions. end Orka.Transforms.SIMD_Quaternions;
Rename constant Zero_Rotation to Identity
transforms: Rename constant Zero_Rotation to Identity Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
61803dfb718406594e5cf48c99556c90ef0b98d1
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers.URLs; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; begin if P /= null then for I in P.Permissions'Range loop if Context.Has_Permission (P.Permissions (I)) then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Perm : constant Security.Controllers.URLs.URL_Controller_Access := new Security.Controllers.URLs.URL_Controller; begin Perm.Manager := Policy'Unchecked_Access; Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Perm.Manager); Policy.Manager.Add_Permission (Name => "url", Permission => Perm.all'Access); end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers.URLs; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; begin if P /= null then for I in P.Permissions'Range loop if Context.Has_Permission (P.Permissions (I)) then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Perm : constant Security.Controllers.URLs.URL_Controller_Access := new Security.Controllers.URLs.URL_Controller; begin Perm.Manager := Policy'Unchecked_Access; Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Perm.Manager); if not Policy.Manager.Has_Controller (P_URL.Permission) then Policy.Manager.Add_Permission (Name => "url", Permission => Perm.all'Access); end if; end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
Check that the policy manager has a URL permission controller
Check that the policy manager has a URL permission controller
Ada
apache-2.0
Letractively/ada-security
fc0480c641dbc90273702537457bdc166893c847
src/tests/ahven/util-xunit.adb
src/tests/ahven/util-xunit.adb
----------------------------------------------------------------------- -- util-xunit - Unit tests on top of AHven -- Copyright (C) 2011, 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.Directories; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Calendar; with Ahven.Listeners.Basic; with Ahven.XML_Runner; with Ahven.Text_Runner; with Ahven.AStrings; with Util.Tests; with Util.Strings; package body Util.XUnit is function Image (Time : in Duration) return String; procedure Report_XML_Summary (Path : in String; Result : in Ahven.Results.Result_Collection; Time : in Duration); -- ------------------------------ -- Build a message from a string (Adaptation for AUnit API). -- ------------------------------ function Format (S : in String) return Message_String is begin return S; end Format; -- ------------------------------ -- Build a message with the source and line number. -- ------------------------------ function Build_Message (Message : in String; Source : in String; Line : in Natural) return String is L : constant String := Natural'Image (Line); begin return Source & ":" & L (2 .. L'Last) & ": " & Message; end Build_Message; procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class); procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class) is begin Test_Case'Class (T).Run_Test; end Run_Test_Case; overriding procedure Initialize (T : in out Test_Case) is begin Ahven.Framework.Add_Test_Routine (T, Run_Test_Case'Access, "Test case"); end Initialize; -- ------------------------------ -- Return the name of the test case. -- ------------------------------ overriding function Get_Name (T : Test_Case) return String is begin return Test_Case'Class (T).Name; end Get_Name; -- maybe_overriding procedure Assert (T : in Test_Case; Condition : in Boolean; Message : in String := "Test failed"; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; -- ------------------------------ -- Check that the value matches what we expect. -- ------------------------------ procedure Assert (T : in Test; Condition : in Boolean; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; First_Test : Test_Object_Access := null; -- ------------------------------ -- Register a test object in the test suite. -- ------------------------------ procedure Register (T : in Test_Object_Access) is begin T.Next := First_Test; First_Test := T; end Register; -- ------------------------------ -- Report passes, skips, failures, and errors from the result collection. -- ------------------------------ procedure Report_Results (Result : in Ahven.Results.Result_Collection; Time : in Duration) is T_Count : constant Integer := Ahven.Results.Test_Count (Result); F_Count : constant Integer := Ahven.Results.Failure_Count (Result); S_Count : constant Integer := Ahven.Results.Skipped_Count (Result); E_Count : constant Integer := Ahven.Results.Error_Count (Result); begin if F_Count > 0 then Ahven.Text_Runner.Print_Failures (Result, 0); end if; if E_Count > 0 then Ahven.Text_Runner.Print_Errors (Result, 0); end if; Ada.Text_IO.Put_Line ("Tests run:" & Integer'Image (T_Count - S_Count) & ", Failures:" & Integer'Image (F_Count) & ", Errors:" & Integer'Image (E_Count) & ", Skipped:" & Integer'Image (S_Count) & ", Time elapsed:" & Duration'Image (Time)); end Report_Results; function Image (Time : in Duration) return String is Result : constant String := Duration'Image (Time); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Image; -- ------------------------------ -- Write a XML summary report in the JUnit format so that the result file -- can be used by Jenkins performance plugin. -- ------------------------------ procedure Report_XML_Summary (Path : in String; Result : in Ahven.Results.Result_Collection; Time : in Duration) is use Ahven.Results; File : Ada.Text_IO.File_Type; Group : Result_Collection_Cursor; Iter : Result_Collection_Cursor; Test : Result_Collection_Access; begin Ada.Text_IO.Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Path); Ada.Text_IO.Put_Line (File, "<?xml version='1.0'?>"); Ada.Text_IO.Put (File, "<testsuite "); Ada.Text_IO.Put (File, "errors='" & Util.Strings.Image (Error_Count (Result)) & "' "); Ada.Text_IO.Put (File, "failures='" & Util.Strings.Image (Failure_Count (Result)) & "' "); Ada.Text_IO.Put (File, "tests='" & Util.Strings.Image (Test_Count (Result)) & "' "); Ada.Text_IO.Put (File, "time='" & Image (Time) & "' "); Ada.Text_IO.Put (File, "name='"); Ada.Text_IO.Put (File, Ahven.AStrings.To_String (Get_Test_Name (Result))); Ada.Text_IO.Put_Line (File, "'>"); Group := First_Child (Result); while Is_Valid (Group) loop Iter := First_Child (Data (Group).all); while Is_Valid (Iter) loop Test := Data (Iter); Ada.Text_IO.Put (File, "<testcase name='"); Ada.Text_IO.Put (File, Ahven.AStrings.To_String (Get_Test_Name (Test.all))); Ada.Text_IO.Put (File, "' errors='"); Ada.Text_IO.Put (File, Util.Strings.Image (Error_Count (Test.all))); Ada.Text_IO.Put (File, "' failures='"); Ada.Text_IO.Put (File, Util.Strings.Image (Failure_Count (Test.all))); Ada.Text_IO.Put (File, "' tests='"); Ada.Text_IO.Put (File, Util.Strings.Image (Test_Count (Test.all))); Ada.Text_IO.Put (File, "' time='"); Ada.Text_IO.Put (File, Image (Get_Execution_Time (Test.all))); Ada.Text_IO.Put_Line (File, "'/>"); Iter := Next (Iter); end loop; Group := Next (Group); end loop; Ada.Text_IO.Put_Line (File, "</testsuite>"); Ada.Text_IO.Close (File); end Report_XML_Summary; -- ------------------------------ -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. -- ------------------------------ procedure Harness (Output : in Ada.Strings.Unbounded.Unbounded_String; XML : in Boolean; Result : out Status) is use Ahven.Listeners.Basic; use Ahven.Framework; use Ahven.Results; use type Ada.Calendar.Time; Tests : constant Access_Test_Suite := Suite; T : Test_Object_Access := First_Test; Listener : Ahven.Listeners.Basic.Basic_Listener; Timeout : constant Test_Duration := Test_Duration (Util.Tests.Get_Test_Timeout ("all")); Out_Dir : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Start : Ada.Calendar.Time; Dt : Duration; begin while T /= null loop Ahven.Framework.Add_Static_Test (Tests.all, T.Test.all); T := T.Next; end loop; Set_Output_Capture (Listener, True); if not Ada.Directories.Exists (Out_Dir) then Ada.Directories.Create_Path (Out_Dir); end if; Ahven.Framework.Set_Logging (Util.Tests.Verbose); Start := Ada.Calendar.Clock; Ahven.Framework.Execute (Tests.all, Listener, Timeout); Dt := Ada.Calendar.Clock - Start; Report_Results (Listener.Main_Result, Dt); Ahven.XML_Runner.Report_Results (Listener.Main_Result, Out_Dir); if (Error_Count (Listener.Main_Result) > 0) or (Failure_Count (Listener.Main_Result) > 0) then Result := Failure; else Result := Success; end if; if XML then Report_XML_Summary (Ada.Strings.Unbounded.To_String (Output), Listener.Main_Result, Dt); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot create file"); Result := Failure; end Harness; end Util.XUnit;
----------------------------------------------------------------------- -- util-xunit - Unit tests on top of AHven -- Copyright (C) 2011, 2016, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Calendar; with Ahven.Listeners.Basic; with Ahven.XML_Runner; with Ahven.Text_Runner; with Ahven.AStrings; with Util.Tests; with Util.Strings; package body Util.XUnit is function Image (Time : in Duration) return String; procedure Report_XML_Summary (Path : in String; Result : in Ahven.Results.Result_Collection; Time : in Duration); -- ------------------------------ -- Build a message from a string (Adaptation for AUnit API). -- ------------------------------ function Format (S : in String) return Message_String is begin return S; end Format; -- ------------------------------ -- Build a message with the source and line number. -- ------------------------------ function Build_Message (Message : in String; Source : in String; Line : in Natural) return String is L : constant String := Natural'Image (Line); begin return Source & ":" & L (2 .. L'Last) & ": " & Message; end Build_Message; procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class); procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class) is begin Test_Case'Class (T).Run_Test; end Run_Test_Case; overriding procedure Initialize (T : in out Test_Case) is begin Ahven.Framework.Add_Test_Routine (T, Run_Test_Case'Access, "Test case"); end Initialize; -- ------------------------------ -- Return the name of the test case. -- ------------------------------ overriding function Get_Name (T : Test_Case) return String is begin return Test_Case'Class (T).Name; end Get_Name; -- maybe_overriding procedure Assert (T : in Test_Case; Condition : in Boolean; Message : in String := "Test failed"; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; -- ------------------------------ -- Check that the value matches what we expect. -- ------------------------------ procedure Assert (T : in Test; Condition : in Boolean; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; First_Test : Test_Object_Access := null; -- ------------------------------ -- Register a test object in the test suite. -- ------------------------------ procedure Register (T : in Test_Object_Access) is begin T.Next := First_Test; First_Test := T; end Register; -- ------------------------------ -- Report passes, skips, failures, and errors from the result collection. -- ------------------------------ procedure Report_Results (Result : in Ahven.Results.Result_Collection; Label : in String; Time : in Duration) is T_Count : constant Integer := Ahven.Results.Test_Count (Result); F_Count : constant Integer := Ahven.Results.Failure_Count (Result); S_Count : constant Integer := Ahven.Results.Skipped_Count (Result); E_Count : constant Integer := Ahven.Results.Error_Count (Result); begin if F_Count > 0 then Ahven.Text_Runner.Print_Failures (Result, 0); end if; if E_Count > 0 then Ahven.Text_Runner.Print_Errors (Result, 0); end if; Ada.Text_IO.Put_Line (Label & "Tests run:" & Integer'Image (T_Count - S_Count) & ", Failures:" & Integer'Image (F_Count) & ", Errors:" & Integer'Image (E_Count) & ", Skipped:" & Integer'Image (S_Count) & ", Time elapsed:" & Duration'Image (Time)); end Report_Results; function Image (Time : in Duration) return String is Result : constant String := Duration'Image (Time); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Image; -- ------------------------------ -- Write a XML summary report in the JUnit format so that the result file -- can be used by Jenkins performance plugin. -- ------------------------------ procedure Report_XML_Summary (Path : in String; Result : in Ahven.Results.Result_Collection; Time : in Duration) is use Ahven.Results; File : Ada.Text_IO.File_Type; Group : Result_Collection_Cursor; Iter : Result_Collection_Cursor; Test : Result_Collection_Access; begin Ada.Text_IO.Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Path); Ada.Text_IO.Put_Line (File, "<?xml version='1.0'?>"); Ada.Text_IO.Put (File, "<testsuite "); Ada.Text_IO.Put (File, "errors='" & Util.Strings.Image (Error_Count (Result)) & "' "); Ada.Text_IO.Put (File, "failures='" & Util.Strings.Image (Failure_Count (Result)) & "' "); Ada.Text_IO.Put (File, "tests='" & Util.Strings.Image (Test_Count (Result)) & "' "); Ada.Text_IO.Put (File, "time='" & Image (Time) & "' "); Ada.Text_IO.Put (File, "name='"); Ada.Text_IO.Put (File, Ahven.AStrings.To_String (Get_Test_Name (Result))); Ada.Text_IO.Put_Line (File, "'>"); Group := First_Child (Result); while Is_Valid (Group) loop Iter := First_Child (Data (Group).all); while Is_Valid (Iter) loop Test := Data (Iter); Ada.Text_IO.Put (File, "<testcase name='"); Ada.Text_IO.Put (File, Ahven.AStrings.To_String (Get_Test_Name (Test.all))); Ada.Text_IO.Put (File, "' errors='"); Ada.Text_IO.Put (File, Util.Strings.Image (Error_Count (Test.all))); Ada.Text_IO.Put (File, "' failures='"); Ada.Text_IO.Put (File, Util.Strings.Image (Failure_Count (Test.all))); Ada.Text_IO.Put (File, "' tests='"); Ada.Text_IO.Put (File, Util.Strings.Image (Test_Count (Test.all))); Ada.Text_IO.Put (File, "' time='"); Ada.Text_IO.Put (File, Image (Get_Execution_Time (Test.all))); Ada.Text_IO.Put_Line (File, "'/>"); Iter := Next (Iter); end loop; Group := Next (Group); end loop; Ada.Text_IO.Put_Line (File, "</testsuite>"); Ada.Text_IO.Close (File); end Report_XML_Summary; -- ------------------------------ -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. -- ------------------------------ procedure Harness (Output : in String; XML : in Boolean; Label : in String; Result : out Status) is use Ahven.Listeners.Basic; use Ahven.Framework; use Ahven.Results; use type Ada.Calendar.Time; Tests : constant Access_Test_Suite := Suite; T : Test_Object_Access := First_Test; Listener : Ahven.Listeners.Basic.Basic_Listener; Timeout : constant Test_Duration := Test_Duration (Util.Tests.Get_Test_Timeout ("all")); Out_Dir : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Start : Ada.Calendar.Time; Dt : Duration; begin while T /= null loop Ahven.Framework.Add_Static_Test (Tests.all, T.Test.all); T := T.Next; end loop; Set_Output_Capture (Listener, True); if not Ada.Directories.Exists (Out_Dir) then Ada.Directories.Create_Path (Out_Dir); end if; Ahven.Framework.Set_Logging (Util.Tests.Verbose); Start := Ada.Calendar.Clock; Ahven.Framework.Execute (Tests.all, Listener, Timeout); Dt := Ada.Calendar.Clock - Start; Report_Results (Listener.Main_Result, Label, Dt); Ahven.XML_Runner.Report_Results (Listener.Main_Result, Out_Dir); if (Error_Count (Listener.Main_Result) > 0) or (Failure_Count (Listener.Main_Result) > 0) then Result := Failure; else Result := Success; end if; if XML then Report_XML_Summary (Output, Listener.Main_Result, Dt); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot create file"); Result := Failure; end Harness; end Util.XUnit;
Add Label parameter to Harness procedure and print the Label before the test summary report
Add Label parameter to Harness procedure and print the Label before the test summary report
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
176af9668fb68258418d6eaa232b3079484a80f5
regtests/util-dates-tests.ads
regtests/util-dates-tests.ads
----------------------------------------------------------------------- -- util-dates-tests - Test for dates -- Copyright (C) 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Dates.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test converting a date in ISO8601. procedure Test_ISO8601_Image (T : in out Test); -- Test converting a string in ISO8601 into a date. procedure Test_ISO8601_Value (T : in out Test); -- Test value convertion errors. procedure Test_ISO8601_Error (T : in out Test); -- Test Is_Same_Day operation. procedure Test_Is_Same_Day (T : in out Test); end Util.Dates.Tests;
----------------------------------------------------------------------- -- util-dates-tests - Test for dates -- Copyright (C) 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Dates.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test converting a date in ISO8601. procedure Test_ISO8601_Image (T : in out Test); -- Test converting a string in ISO8601 into a date. procedure Test_ISO8601_Value (T : in out Test); -- Test value convertion errors. procedure Test_ISO8601_Error (T : in out Test); -- Test Is_Same_Day operation. procedure Test_Is_Same_Day (T : in out Test); -- Test Get_Day_Count operation. procedure Test_Get_Day_Count (T : in out Test); end Util.Dates.Tests;
Declare Test_Get_Day_Count
Declare Test_Get_Day_Count
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
930494d69925584ed904083d527332b370d4fdc5
mat/src/mat-targets-probes.ads
mat/src/mat-targets-probes.ads
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Events; with MAT.Events.Targets; with MAT.Events.Probes; package MAT.Targets.Probes is type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record Target : Target_Type_Access; Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Process : Target_Process_Type_Access; Events : MAT.Events.Targets.Target_Events_Access; end record; type Process_Probe_Type_Access is access all Process_Probe_Type'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (Probe : in out Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Extract the probe information from the message. overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type); procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access); -- Initialize the target object to prepare for reading process events. procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); private procedure Probe_Begin (Probe : in out Process_Probe_Type; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message); end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Events; with MAT.Events.Targets; with MAT.Events.Probes; package MAT.Targets.Probes is type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record Target : Target_Type_Access; Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Events : MAT.Events.Targets.Target_Events_Access; end record; type Process_Probe_Type_Access is access all Process_Probe_Type'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Extract the probe information from the message. overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type); procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access); -- Initialize the target object to prepare for reading process events. procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); private procedure Probe_Begin (Probe : in Process_Probe_Type; Id : in MAT.Events.Targets.Probe_Index_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message); end MAT.Targets.Probes;
Fix Create_Process and Probe_Begin for the new MAT.Events.Probes implementation
Fix Create_Process and Probe_Begin for the new MAT.Events.Probes implementation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
301c183a9ad5c80cce2a5b1450d9addb0260c4bb
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Events.Faces.Actions; with ADO.Utils; with ADO.Sessions.Entities; with ADO.Sessions; with ADO.Queries; with ADO.Datasets; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Events.Action_Method; with AWA.Services.Contexts; package body AWA.Workspaces.Beans is package ASC renames AWA.Services.Contexts; -- Get the value identified by the name. overriding function Get_Value (From : in Member_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name); end Get_Value; overriding procedure Load (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Load; overriding procedure Delete (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Delete_Member (Bean.Get_Id); end Delete; -- ------------------------------ -- Create the Member_Bean bean instance. -- ------------------------------ function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_Bean_Access := new Member_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Member_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Invitation_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "inviter" then return From.Inviter.Get_Value ("name"); else return AWA.Workspaces.Models.Invitation_Bean (From).Get_Value (Name); end if; end Get_Value; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key), Invitation => Bean, Inviter => Bean.Inviter); exception when others => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key)); end Accept_Invitation; overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Send_Invitation (Bean); end Send; -- ------------------------------ -- Create the Invitation_Bean bean instance. -- ------------------------------ function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Invitation_Bean_Access := new Invitation_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Invitation_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Action; -- ------------------------------ -- Event action called to create the workspace when the given event is posted. -- ------------------------------ procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Bean, Event); WS : AWA.Workspaces.Models.Workspace_Ref; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (Session => DB, Context => Ctx, Workspace => WS); Ctx.Commit; end Create; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean, Method => Action, Name => "action"); package Create_Binding is new AWA.Events.Action_Method.Bind (Name => "create", Bean => Workspaces_Bean, Method => Create); Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Workspaces_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Workspaces_Bean_Access := new Workspaces_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Workspaces_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" then return Util.Beans.Objects.To_Object (Value => From.Members_Bean, Storage => Util.Beans.Objects.STATIC); else return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Load the list of members. -- ------------------------------ overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Into.Module.Get_Session; Query : ADO.Queries.Context; Count_Query : ADO.Queries.Context; First : constant Natural := (Into.Page - 1) * Into.Page_Size; begin Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "page_table", -- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, -- Session => Session); Query.Bind_Param (Name => "user_id", Value => User); Count_Query.Bind_Param (Name => "user_id", Value => User); AWA.Workspaces.Models.List (Into.Members, Session, Query); Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); end Load; -- ------------------------------ -- Create the Member_List_Bean bean instance. -- ------------------------------ function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_List_Bean_Access := new Member_List_Bean; begin Object.Module := Module; Object.Members_Bean := Object.Members'Access; Object.Page_Size := 20; Object.Page := 1; Object.Count := 0; return Object.all'Access; end Create_Member_List_Bean; end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Events.Faces.Actions; with ADO.Utils; with ADO.Sessions.Entities; with ADO.Sessions; with ADO.Queries; with ADO.Datasets; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Events.Action_Method; with AWA.Services.Contexts; package body AWA.Workspaces.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Member_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name -- ------------------------------ overriding procedure Set_Value (Item : in out Member_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then Item.Set_Id (ADO.Utils.To_Identifier (Value)); else AWA.Workspaces.Models.Member_Bean (Item).Set_Value (Name, Value); end if; end Set_Value; overriding procedure Load (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Load; overriding procedure Delete (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Delete_Member (Bean.Get_Id); end Delete; -- ------------------------------ -- Create the Member_Bean bean instance. -- ------------------------------ function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_Bean_Access := new Member_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Member_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Invitation_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "inviter" then return From.Inviter.Get_Value ("name"); else return AWA.Workspaces.Models.Invitation_Bean (From).Get_Value (Name); end if; end Get_Value; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key), Invitation => Bean, Inviter => Bean.Inviter); exception when others => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key)); end Accept_Invitation; overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Send_Invitation (Bean); end Send; -- ------------------------------ -- Create the Invitation_Bean bean instance. -- ------------------------------ function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Invitation_Bean_Access := new Invitation_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Invitation_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Action; -- ------------------------------ -- Event action called to create the workspace when the given event is posted. -- ------------------------------ procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Bean, Event); WS : AWA.Workspaces.Models.Workspace_Ref; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (Session => DB, Context => Ctx, Workspace => WS); Ctx.Commit; end Create; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean, Method => Action, Name => "action"); package Create_Binding is new AWA.Events.Action_Method.Bind (Name => "create", Bean => Workspaces_Bean, Method => Create); Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Workspaces_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Workspaces_Bean_Access := new Workspaces_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Workspaces_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" then return Util.Beans.Objects.To_Object (Value => From.Members_Bean, Storage => Util.Beans.Objects.STATIC); else return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Load the list of members. -- ------------------------------ overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Into.Module.Get_Session; Query : ADO.Queries.Context; Count_Query : ADO.Queries.Context; First : constant Natural := (Into.Page - 1) * Into.Page_Size; begin Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "page_table", -- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, -- Session => Session); Query.Bind_Param (Name => "user_id", Value => User); Count_Query.Bind_Param (Name => "user_id", Value => User); AWA.Workspaces.Models.List (Into.Members, Session, Query); Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); end Load; -- ------------------------------ -- Create the Member_List_Bean bean instance. -- ------------------------------ function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_List_Bean_Access := new Member_List_Bean; begin Object.Module := Module; Object.Members_Bean := Object.Members'Access; Object.Page_Size := 20; Object.Page := 1; Object.Count := 0; return Object.all'Access; end Create_Member_List_Bean; end AWA.Workspaces.Beans;
Implement the Set_Value procedure on the Member_Bean type
Implement the Set_Value procedure on the Member_Bean type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a9458fa88347fd6157f96de829b3d1d7087d58f6
src/gl/interface/gl-objects-queries.ads
src/gl/interface/gl-objects-queries.ads
-- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with GL.Low_Level; package GL.Objects.Queries is pragma Preelaborate; type Query_Type is (Transform_Feedback_Overflow, Transform_Feedback_Stream_Overflow, Time_Elapsed, Samples_Passed, Any_Samples_Passed, Primitives_Generated, Transform_Feedback_Primitives_Written, Any_Samples_Passed_Conservative, Timestamp); -- Has to be defined here because of the subtype declaration below for Query_Type use (Transform_Feedback_Overflow => 16#82EC#, Transform_Feedback_Stream_Overflow => 16#82ED#, Time_Elapsed => 16#88BF#, Samples_Passed => 16#8914#, Any_Samples_Passed => 16#8C2F#, Primitives_Generated => 16#8C87#, Transform_Feedback_Primitives_Written => 16#8C88#, Any_Samples_Passed_Conservative => 16#8D6A#, Timestamp => 16#8E28#); for Query_Type'Size use Low_Level.Enum'Size; subtype Async_Query_Type is Query_Type range Transform_Feedback_Overflow .. Any_Samples_Passed_Conservative; subtype Timestamp_Query_Type is Query_Type range Timestamp .. Timestamp; subtype Stream_Query_Type is Query_Type with Static_Predicate => Stream_Query_Type in Primitives_Generated | Transform_Feedback_Primitives_Written | Transform_Feedback_Stream_Overflow; type Query_Mode is (Wait, No_Wait, By_Region_Wait, By_Region_No_Wait, Wait_Inverted, No_Wait_Inverted, By_Region_Wait_Inverted, By_Region_No_Wait_Inverted); type Query_Param is (Result, Result_Available, Result_No_Wait); type Target_Param is (Counter_Bits, Current_Query); type Query (Target : Query_Type) is new GL_Object with private; overriding procedure Initialize_Id (Object : in out Query); overriding procedure Delete_Id (Object : in out Query); overriding function Identifier (Object : Query) return Types.Debug.Identifier is (Types.Debug.Query); type Active_Query is limited new Ada.Finalization.Limited_Controlled with private; type Conditional_Render is limited new Ada.Finalization.Limited_Controlled with private; function Begin_Query (Object : in out Query; Target : in Async_Query_Type; Index : in Natural := 0) return Active_Query'Class with Pre => (if Target not in Stream_Query_Type then Index = 0); -- Start an asynchronous query. The value returned is of a controlled -- type, meaning you must assign it to some local variable, so that -- the query will be automatically ended when the variable goes out -- of scope. -- -- Queries of type Timestamp are not used within a scope. For such -- a query you can record the time into the query object by calling -- Record_Current_Time. -- -- Certain queries support multiple query operations; one for each -- index. The index represents the vertex output stream used in a -- Geometry Shader. These targets are: -- -- * Primitives_Generated -- * Transform_Feedback_Primitives_Written -- * Transform_Feedback_Stream_Overflow -- -- The query should be issued while within a transform feedback scope -- for one of the following targets: -- -- * Transform_Feedback_Primitives_Written -- * Transform_Feedback_Overflow -- * Transform_Feedback_Stream_Overflow function Begin_Conditional_Render (Object : in out Query; Mode : in Query_Mode) return Conditional_Render'Class; -- Start a conditional rendering. The value returned is of a controlled -- type, meaning you must assign it to some local variable, so that -- the rendering will be automatically ended when the variable goes -- out of scope. -- -- If Mode is (By_Region_)Wait, then OpenGL will wait until the result -- becomes available and uses the value of the result to determine -- whether to execute or discard rendering commands. -- -- If Mode is *_Inverted, then the condition is inverted, meaning it -- will execute rendering commands if the query result is zero/false. -- -- If Mode is (By_Region_)No_Wait(_Inverted), then OpenGL may choose -- to execute rendering commands while the result of the query is not -- available. function Result_Available (Object : in out Query) return Boolean; -- Return true if a result is available, false otherwise. This function -- can be used to avoid calling Result (and thereby stalling the CPU) -- when the result is not yet available. function Result_If_Available (Object : in out Query; Default_Value : Boolean) return Boolean; -- Return the result if available, otherwise return the default value function Result_If_Available (Object : in out Query; Default_Value : Natural) return Natural; -- Return the result if available, otherwise return the default value function Result (Object : in out Query) return Boolean; -- Return the result. If the result is not yet available, then the -- CPU will stall until the result becomes available. This means -- that if you do not call Result_Available, then this function call -- will make the query synchronous. function Result (Object : in out Query) return Natural; -- Return the result. If the result is not yet available, then the -- CPU will stall until the result becomes available. This means -- that if you do not call Result_Available, then this function call -- will make the query synchronous. function Result_Bits (Target : in Query_Type) return Natural; procedure Record_Current_Time (Object : in out Query); -- Record the time when the GPU has completed all previous commands -- in a query object. The result must be retrieved asynchronously using -- one of the Result functions. function Get_Current_Time return Long; -- Return the time when the GPU has received (but not necessarily -- completed) all previous commands. Calling this function stalls the CPU. private for Query_Mode use (Wait => 16#8E13#, No_Wait => 16#8E14#, By_Region_Wait => 16#8E15#, By_Region_No_Wait => 16#8E16#, Wait_Inverted => 16#8E17#, No_Wait_Inverted => 16#8E18#, By_Region_Wait_Inverted => 16#8E19#, By_Region_No_Wait_Inverted => 16#8E1A#); for Query_Mode'Size use Low_Level.Enum'Size; for Target_Param use (Counter_Bits => 16#8864#, Current_Query => 16#8865#); for Target_Param'Size use Low_Level.Enum'Size; for Query_Param use (Result => 16#8866#, Result_Available => 16#8867#, Result_No_Wait => 16#9194#); for Query_Param'Size use Low_Level.Enum'Size; type Query (Target : Query_Type) is new GL_Object with null record; type Active_Query is limited new Ada.Finalization.Limited_Controlled with record Target : Query_Type; Index : Natural; Finalized : Boolean; end record; overriding procedure Finalize (Object : in out Active_Query); type Conditional_Render is limited new Ada.Finalization.Limited_Controlled with record Finalized : Boolean; end record; overriding procedure Finalize (Object : in out Conditional_Render); end GL.Objects.Queries;
-- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with GL.Low_Level; package GL.Objects.Queries is pragma Preelaborate; type Query_Type is (Transform_Feedback_Overflow, Transform_Feedback_Stream_Overflow, Vertices_Submitted, Primitives_Submitted, Vertex_Shader_Invocations, Tess_Control_Shader_Invocations, Tess_Evaluation_Shader_Invocations, Geometry_Shader_Primitives_Emitted, Fragment_Shader_Invocations, Compute_Shader_Invocations, Clipping_Input_Primitives, Clipping_Output_Primitives, Geometry_Shader_Invocations, Time_Elapsed, Samples_Passed, Any_Samples_Passed, Primitives_Generated, Transform_Feedback_Primitives_Written, Any_Samples_Passed_Conservative, Timestamp); -- Has to be defined here because of the subtype declaration below for Query_Type use (Transform_Feedback_Overflow => 16#82EC#, Transform_Feedback_Stream_Overflow => 16#82ED#, Vertices_Submitted => 16#82EE#, Primitives_Submitted => 16#82EF#, Vertex_Shader_Invocations => 16#82F0#, Tess_Control_Shader_Invocations => 16#82F1#, Tess_Evaluation_Shader_Invocations => 16#82F2#, Geometry_Shader_Primitives_Emitted => 16#82F3#, Fragment_Shader_Invocations => 16#82F4#, Compute_Shader_Invocations => 16#82F5#, Clipping_Input_Primitives => 16#82F6#, Clipping_Output_Primitives => 16#82F7#, Geometry_Shader_Invocations => 16#887F#, Time_Elapsed => 16#88BF#, Samples_Passed => 16#8914#, Any_Samples_Passed => 16#8C2F#, Primitives_Generated => 16#8C87#, Transform_Feedback_Primitives_Written => 16#8C88#, Any_Samples_Passed_Conservative => 16#8D6A#, Timestamp => 16#8E28#); for Query_Type'Size use Low_Level.Enum'Size; subtype Async_Query_Type is Query_Type range Transform_Feedback_Overflow .. Any_Samples_Passed_Conservative; subtype Timestamp_Query_Type is Query_Type range Timestamp .. Timestamp; subtype Stream_Query_Type is Query_Type with Static_Predicate => Stream_Query_Type in Primitives_Generated | Transform_Feedback_Primitives_Written | Transform_Feedback_Stream_Overflow; type Query_Mode is (Wait, No_Wait, By_Region_Wait, By_Region_No_Wait, Wait_Inverted, No_Wait_Inverted, By_Region_Wait_Inverted, By_Region_No_Wait_Inverted); type Query_Param is (Result, Result_Available, Result_No_Wait); type Target_Param is (Counter_Bits, Current_Query); type Query (Target : Query_Type) is new GL_Object with private; overriding procedure Initialize_Id (Object : in out Query); overriding procedure Delete_Id (Object : in out Query); overriding function Identifier (Object : Query) return Types.Debug.Identifier is (Types.Debug.Query); type Active_Query is limited new Ada.Finalization.Limited_Controlled with private; type Conditional_Render is limited new Ada.Finalization.Limited_Controlled with private; function Begin_Query (Object : in out Query; Target : in Async_Query_Type; Index : in Natural := 0) return Active_Query'Class with Pre => (if Target not in Stream_Query_Type then Index = 0); -- Start an asynchronous query. The value returned is of a controlled -- type, meaning you must assign it to some local variable, so that -- the query will be automatically ended when the variable goes out -- of scope. -- -- Queries of type Timestamp are not used within a scope. For such -- a query you can record the time into the query object by calling -- Record_Current_Time. -- -- Certain queries support multiple query operations; one for each -- index. The index represents the vertex output stream used in a -- Geometry Shader. These targets are: -- -- * Primitives_Generated -- * Transform_Feedback_Primitives_Written -- * Transform_Feedback_Stream_Overflow -- -- The query should be issued while within a transform feedback scope -- for one of the following targets: -- -- * Transform_Feedback_Primitives_Written -- * Transform_Feedback_Overflow -- * Transform_Feedback_Stream_Overflow function Begin_Conditional_Render (Object : in out Query; Mode : in Query_Mode) return Conditional_Render'Class; -- Start a conditional rendering. The value returned is of a controlled -- type, meaning you must assign it to some local variable, so that -- the rendering will be automatically ended when the variable goes -- out of scope. -- -- If Mode is (By_Region_)Wait, then OpenGL will wait until the result -- becomes available and uses the value of the result to determine -- whether to execute or discard rendering commands. -- -- If Mode is *_Inverted, then the condition is inverted, meaning it -- will execute rendering commands if the query result is zero/false. -- -- If Mode is (By_Region_)No_Wait(_Inverted), then OpenGL may choose -- to execute rendering commands while the result of the query is not -- available. function Result_Available (Object : in out Query) return Boolean; -- Return true if a result is available, false otherwise. This function -- can be used to avoid calling Result (and thereby stalling the CPU) -- when the result is not yet available. function Result_If_Available (Object : in out Query; Default_Value : Boolean) return Boolean; -- Return the result if available, otherwise return the default value function Result_If_Available (Object : in out Query; Default_Value : Natural) return Natural; -- Return the result if available, otherwise return the default value function Result (Object : in out Query) return Boolean; -- Return the result. If the result is not yet available, then the -- CPU will stall until the result becomes available. This means -- that if you do not call Result_Available, then this function call -- will make the query synchronous. function Result (Object : in out Query) return Natural; -- Return the result. If the result is not yet available, then the -- CPU will stall until the result becomes available. This means -- that if you do not call Result_Available, then this function call -- will make the query synchronous. function Result_Bits (Target : in Query_Type) return Natural; procedure Record_Current_Time (Object : in out Query); -- Record the time when the GPU has completed all previous commands -- in a query object. The result must be retrieved asynchronously using -- one of the Result functions. function Get_Current_Time return Long; -- Return the time when the GPU has received (but not necessarily -- completed) all previous commands. Calling this function stalls the CPU. private for Query_Mode use (Wait => 16#8E13#, No_Wait => 16#8E14#, By_Region_Wait => 16#8E15#, By_Region_No_Wait => 16#8E16#, Wait_Inverted => 16#8E17#, No_Wait_Inverted => 16#8E18#, By_Region_Wait_Inverted => 16#8E19#, By_Region_No_Wait_Inverted => 16#8E1A#); for Query_Mode'Size use Low_Level.Enum'Size; for Target_Param use (Counter_Bits => 16#8864#, Current_Query => 16#8865#); for Target_Param'Size use Low_Level.Enum'Size; for Query_Param use (Result => 16#8866#, Result_Available => 16#8867#, Result_No_Wait => 16#9194#); for Query_Param'Size use Low_Level.Enum'Size; type Query (Target : Query_Type) is new GL_Object with null record; type Active_Query is limited new Ada.Finalization.Limited_Controlled with record Target : Query_Type; Index : Natural; Finalized : Boolean; end record; overriding procedure Finalize (Object : in out Active_Query); type Conditional_Render is limited new Ada.Finalization.Limited_Controlled with record Finalized : Boolean; end record; overriding procedure Finalize (Object : in out Conditional_Render); end GL.Objects.Queries;
Add query targets for pipeline statistics
gl: Add query targets for pipeline statistics * Extension ARB_pipeline_statistics_query (OpenGL 4.6) Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
693cf5fa8a531cb6a8528677aa20d15f9976bcad
awa/plugins/awa-comments/src/awa-comments-services.adb
awa/plugins/awa-comments/src/awa-comments-services.adb
----------------------------------------------------------------------- -- awa-comments-logic -- Comments management -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with ADO.Sessions; with ADO.Sessions.Entities; with Ada.Calendar; with Util.Log.Loggers; package body AWA.Comments.Services is use Util.Log; use ADO.Sessions; use AWA.Services; Log : constant Loggers.Logger := Loggers.Create ("AWA.Comments.Services"); -- ------------------------------ -- Create a comment associated with the given database entity. -- The user must have permission to add comments on the given entity. -- ------------------------------ procedure Create_Comment (Model : in Comment_Service; Entity : in ADO.Objects.Object_Key; Message : in String; User : in AWA.Users.Models.User_Ref'Class; Result : out ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Comment : Comment_Ref; Entity_Id : constant ADO.Identifier := ADO.Objects.Get_Value (Entity); begin Log.Info ("Create comment for user {0}", String'(User.Get_Name)); -- -- select from asset inner join acl -- on asset.collection_id = acl.entity_id and acl.entity_type = :entity_type -- where asset.id = :entity_id and acl.user_id = :user_id -- AWA.Permissions.Module.Check (Entity => Entity, Permission => CREATE_COMMENT); Ctx.Start; Comment.Set_Message (Message); Comment.Set_Entity_Id (Entity_Id); Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity)); Comment.Set_User (User); Comment.Set_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; Result := Comment.Get_Id; Log.Info ("Comment {0} created", ADO.Identifier'Image (Result)); end Create_Comment; procedure Find_Comment (Model : in Comment_Service; Id : in ADO.Identifier; Comment : in out Comment_Ref'Class) is begin null; end Find_Comment; -- ------------------------------ -- Delete the comment identified by the given identifier. -- ------------------------------ procedure Delete_Comment (Model : in Comment_Service; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Comment : Comment_Ref; begin Log.Info ("Delete comment {0}", ADO.Identifier'Image (Id)); -- AWA.Permissions.Module.Check (Entity => Entity, Permission => CREATE_COMMENT); Ctx.Start; Comment.Set_Id (Id); Comment.Delete (DB); Ctx.Commit; end Delete_Comment; end AWA.Comments.Services;
----------------------------------------------------------------------- -- awa-comments-logic -- Comments management -- 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 AWA.Services.Contexts; with ADO.Sessions; with ADO.Sessions.Entities; with Ada.Calendar; with Util.Log.Loggers; package body AWA.Comments.Services is use Util.Log; use ADO.Sessions; use AWA.Services; Log : constant Loggers.Logger := Loggers.Create ("AWA.Comments.Services"); -- ------------------------------ -- Create a comment associated with the given database entity. -- The user must have permission to add comments on the given entity. -- ------------------------------ procedure Create_Comment (Model : in Comment_Service; Entity : in ADO.Objects.Object_Key; Message : in String; User : in AWA.Users.Models.User_Ref'Class; Result : out ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Comment : Comment_Ref; Entity_Id : constant ADO.Identifier := ADO.Objects.Get_Value (Entity); begin Log.Info ("Create comment for user {0}", String'(User.Get_Name)); -- -- select from asset inner join acl -- on asset.collection_id = acl.entity_id and acl.entity_type = :entity_type -- where asset.id = :entity_id and acl.user_id = :user_id -- AWA.Permissions.Module.Check (Entity => Entity, Permission => CREATE_COMMENT); Ctx.Start; Comment.Set_Message (Message); Comment.Set_Entity_Id (Entity_Id); Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity)); Comment.Set_Author (User); Comment.Set_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; Result := Comment.Get_Id; Log.Info ("Comment {0} created", ADO.Identifier'Image (Result)); end Create_Comment; procedure Find_Comment (Model : in Comment_Service; Id : in ADO.Identifier; Comment : in out Comment_Ref'Class) is begin null; end Find_Comment; -- ------------------------------ -- Delete the comment identified by the given identifier. -- ------------------------------ procedure Delete_Comment (Model : in Comment_Service; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Comment : Comment_Ref; begin Log.Info ("Delete comment {0}", ADO.Identifier'Image (Id)); -- AWA.Permissions.Module.Check (Entity => Entity, Permission => CREATE_COMMENT); Ctx.Start; Comment.Set_Id (Id); Comment.Delete (DB); Ctx.Commit; end Delete_Comment; end AWA.Comments.Services;
Update the implementation according to the UML model
Update the implementation according to the UML model
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
51cc4202f626ffe7d60215af7e5deae6f4b93ded
awa/plugins/awa-storages/src/awa-storages-servlets.ads
awa/plugins/awa-storages/src/awa-storages-servlets.ads
----------------------------------------------------------------------- -- awa-storages-servlets -- Serve files saved in the storage service -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with ASF.Servlets; with ASF.Requests; with ASF.Responses; -- == Storage Servlet == -- The <tt>Storage_Servlet</tt> type is the servlet that allows to retrieve the file -- content that was uploaded. package AWA.Storages.Servlets is -- The <b>Storage_Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Storage_Servlet is new ASF.Servlets.Servlet with private; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. overriding procedure Initialize (Server : in out Storage_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" overriding procedure Do_Get (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Load the data content that correspond to the GET request and get the name as well -- as mime-type and date. procedure Load (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Data : out ADO.Blob_Ref); private type Storage_Servlet is new ASF.Servlets.Servlet with null record; end AWA.Storages.Servlets;
----------------------------------------------------------------------- -- awa-storages-servlets -- Serve files saved in the storage service -- Copyright (C) 2012, 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.Calendar; with Servlet.Core; with ASF.Requests; with ASF.Responses; -- == Storage Servlet == -- The <tt>Storage_Servlet</tt> type is the servlet that allows to retrieve the file -- content that was uploaded. package AWA.Storages.Servlets is -- The <b>Storage_Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Storage_Servlet is new Servlet.Core.Servlet with private; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. overriding procedure Initialize (Server : in out Storage_Servlet; Context : in Servlet.Core.Servlet_Registry'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" overriding procedure Do_Get (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Load the data content that correspond to the GET request and get the name as well -- as mime-type and date. procedure Load (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Data : out ADO.Blob_Ref); private type Storage_Servlet is new Servlet.Core.Servlet with null record; end AWA.Storages.Servlets;
Use the Servlet.Core package instread of ASF.Servlets
Use the Servlet.Core package instread of ASF.Servlets
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5eacf2e0aefb48c2672ba82d15c9445c3a1c417e
awa/src/awa-modules.adb
awa/src/awa-modules.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- 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 ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with Util.Properties; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Config.Get (Config); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in String := "") return EL.Expressions.Expression is Ctx : EL.Contexts.Default.Default_Context; Value : constant String := Plugin.Get_Config (Name, Default); begin return EL.Expressions.Create_Expression (Value, Ctx); exception when E : others => Log.Error ("Invalid parameter ", E, True); return EL.Expressions.Create_Expression ("", Ctx); end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is procedure Copy (Params : in Util.Properties.Manager'Class); procedure Copy (Params : in Util.Properties.Manager'Class) is begin Plugin.Config.Copy (From => Params, Prefix => Name & ".", Strip => True); end Copy; Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Info ("Module configuration file '{0}' does not exist", Path); end; Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration App.Get_Init_Parameters (Copy'Access); Plugin.Configure (Plugin.Config); exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. -- ------------------------------ procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)) is Iter : Module_Maps.Cursor := Registry.Name_Map.First; begin while Module_Maps.Has_Element (Iter) loop Process (Module_Maps.Element (Iter).all); Module_Maps.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. -- ------------------------------ procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Add_Listener (Into.Listeners, Item); end Add_Listener; -- ------------------------------ -- Find the module with the given name in the application and add the listener to the -- module listener list. -- ------------------------------ procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access) is M : constant Module_Access := Plugin.App.Find_Module (Name); begin if M = null then Log.Error ("Cannot find module {0} to add a lifecycle listener", Name); else M.Add_Listener (Item); end if; end Add_Listener; -- ------------------------------ -- Remove a listener from the module listener list. -- ------------------------------ procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Remove_Listener (Into.Listeners, Item); end Remove_Listener; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Unchecked_Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- 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 ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with Util.Properties; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Config.Get (Config); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in String := "") return EL.Expressions.Expression is type Event_ELResolver is new EL.Contexts.Default.Default_ELResolver with null record; overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object is begin if Base /= null then return EL.Contexts.Default.Default_ELResolver (Resolver).Get_Value (Context, Base, Name); else return Util.Beans.Objects.To_Object (Plugin.Get_Config (To_String (Name), "")); end if; end Get_Value; Resolver : aliased Event_ELResolver; Context : EL.Contexts.Default.Default_Context; Value : constant String := Plugin.Get_Config (Name, Default); begin Context.Set_Resolver (Resolver'Unchecked_Access); return EL.Expressions.Reduce_Expression (EL.Expressions.Create_Expression (Value, Context), Context); exception when E : others => Log.Error ("Invalid parameter ", E, True); return EL.Expressions.Create_Expression ("", Context); end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is procedure Copy (Params : in Util.Properties.Manager'Class); procedure Copy (Params : in Util.Properties.Manager'Class) is begin Plugin.Config.Copy (From => Params, Prefix => Name & ".", Strip => True); end Copy; Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Info ("Module configuration file '{0}' does not exist", Path); end; Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration App.Get_Init_Parameters (Copy'Access); Plugin.Configure (Plugin.Config); exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. -- ------------------------------ procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)) is Iter : Module_Maps.Cursor := Registry.Name_Map.First; begin while Module_Maps.Has_Element (Iter) loop Process (Module_Maps.Element (Iter).all); Module_Maps.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. -- ------------------------------ procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Add_Listener (Into.Listeners, Item); end Add_Listener; -- ------------------------------ -- Find the module with the given name in the application and add the listener to the -- module listener list. -- ------------------------------ procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access) is M : constant Module_Access := Plugin.App.Find_Module (Name); begin if M = null then Log.Error ("Cannot find module {0} to add a lifecycle listener", Name); else M.Add_Listener (Item); end if; end Add_Listener; -- ------------------------------ -- Remove a listener from the module listener list. -- ------------------------------ procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Remove_Listener (Into.Listeners, Item); end Remove_Listener; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Unchecked_Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
Update the Get_Config function for a better support of EL expressions
Update the Get_Config function for a better support of EL expressions
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5fd563c05da93def285ebd04a6563c9641f13bab
mat/src/mat-targets.ads
mat/src/mat-targets.ads
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols; Console : MAT.Consoles.Console_Access; end record; type Target_Type_Access is access all Target_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Process : out Target_Process_Type_Access); private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); end MAT.Targets;
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols; Console : MAT.Consoles.Console_Access; end record; type Target_Type_Access is access all Target_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Process : out Target_Process_Type_Access); private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; end MAT.Targets;
Declare the Process_Map and Process_Cursor types
Declare the Process_Map and Process_Cursor types
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
23d8b6265ded6454722c1ab9c702c39eed8b309a
mat/src/gtk/mat-callbacks.adb
mat/src/gtk/mat-callbacks.adb
----------------------------------------------------------------------- -- mat-callbacks - Callbacks for Gtk -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Glib.Main; with Gtk.Main; with Gtk.Widget; with Gtk.Label; with Util.Log.Loggers; with MAT.Commands; package body MAT.Callbacks is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Callbacks"); type Info is record Builder : access Gtkada.Builder.Gtkada_Builder_Record'Class; end record; package Timer_Callback is new Glib.Main.Generic_Sources (MAT.Targets.Gtkmat.Target_Type_Access); Timer : Glib.Main.G_Source_Id; MemTotal : Natural := 1; Target : MAT.Targets.Gtkmat.Target_Type_Access; function Refresh_Timeout (Target : in MAT.Targets.Gtkmat.Target_Type_Access) return Boolean is begin Target.Refresh_Process; return True; end Refresh_Timeout; -- ------------------------------ -- Initialize and register the callbacks. -- ------------------------------ procedure Initialize (Target : in MAT.Targets.Gtkmat.Target_Type_Access; Builder : in Gtkada.Builder.Gtkada_Builder) is begin MAT.Callbacks.Target := Target; Builder.Register_Handler (Handler_Name => "quit", Handler => MAT.Callbacks.On_Menu_Quit'Access); Builder.Register_Handler (Handler_Name => "about", Handler => MAT.Callbacks.On_Menu_About'Access); Builder.Register_Handler (Handler_Name => "close-about", Handler => MAT.Callbacks.On_Close_About'Access); Builder.Register_Handler (Handler_Name => "cmd-sizes", Handler => MAT.Callbacks.On_Btn_Sizes'Access); Timer := Timer_Callback.Timeout_Add (1000, Refresh_Timeout'Access, Target); end Initialize; -- ------------------------------ -- Callback executed when the "quit" action is executed from the menu. -- ------------------------------ procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is begin Gtk.Main.Main_Quit; end On_Menu_Quit; -- ------------------------------ -- Callback executed when the "about" action is executed from the menu. -- ------------------------------ procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is About : constant Gtk.Widget.Gtk_Widget := Gtk.Widget.Gtk_Widget (Object.Get_Object ("about")); begin About.Show; end On_Menu_About; -- ------------------------------ -- Callback executed when the "close-about" action is executed from the about box. -- ------------------------------ procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is About : constant Gtk.Widget.Gtk_Widget := Gtk.Widget.Gtk_Widget (Object.Get_Object ("about")); begin About.Hide; end On_Close_About; -- ------------------------------ -- Callback executed when the "cmd-sizes" action is executed from the "Sizes" action. -- ------------------------------ procedure On_Btn_Sizes (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is pragma Unreferenced (Object); begin MAT.Commands.Sizes_Command (Target.all, ""); end On_Btn_Sizes; end MAT.Callbacks;
----------------------------------------------------------------------- -- mat-callbacks - Callbacks for Gtk -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Glib.Main; with Gtk.Main; with Gtk.Widget; with Gtk.Label; with Util.Log.Loggers; with MAT.Commands; package body MAT.Callbacks is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Callbacks"); type Info is record Builder : access Gtkada.Builder.Gtkada_Builder_Record'Class; end record; package Timer_Callback is new Glib.Main.Generic_Sources (MAT.Targets.Gtkmat.Target_Type_Access); Timer : Glib.Main.G_Source_Id; MemTotal : Natural := 1; Target : MAT.Targets.Gtkmat.Target_Type_Access; function Refresh_Timeout (Target : in MAT.Targets.Gtkmat.Target_Type_Access) return Boolean is begin Target.Refresh_Process; return True; end Refresh_Timeout; -- ------------------------------ -- Initialize and register the callbacks. -- ------------------------------ procedure Initialize (Target : in MAT.Targets.Gtkmat.Target_Type_Access; Builder : in Gtkada.Builder.Gtkada_Builder) is begin MAT.Callbacks.Target := Target; Builder.Register_Handler (Handler_Name => "quit", Handler => MAT.Callbacks.On_Menu_Quit'Access); Builder.Register_Handler (Handler_Name => "about", Handler => MAT.Callbacks.On_Menu_About'Access); Builder.Register_Handler (Handler_Name => "close-about", Handler => MAT.Callbacks.On_Close_About'Access); Builder.Register_Handler (Handler_Name => "cmd-sizes", Handler => MAT.Callbacks.On_Btn_Sizes'Access); Builder.Register_Handler (Handler_Name => "cmd-threads", Handler => MAT.Callbacks.On_Btn_Threads'Access); Timer := Timer_Callback.Timeout_Add (1000, Refresh_Timeout'Access, Target); end Initialize; -- ------------------------------ -- Callback executed when the "quit" action is executed from the menu. -- ------------------------------ procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is begin Gtk.Main.Main_Quit; end On_Menu_Quit; -- ------------------------------ -- Callback executed when the "about" action is executed from the menu. -- ------------------------------ procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is About : constant Gtk.Widget.Gtk_Widget := Gtk.Widget.Gtk_Widget (Object.Get_Object ("about")); begin About.Show; end On_Menu_About; -- ------------------------------ -- Callback executed when the "close-about" action is executed from the about box. -- ------------------------------ procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is About : constant Gtk.Widget.Gtk_Widget := Gtk.Widget.Gtk_Widget (Object.Get_Object ("about")); begin About.Hide; end On_Close_About; -- ------------------------------ -- Callback executed when the "cmd-sizes" action is executed from the "Sizes" action. -- ------------------------------ procedure On_Btn_Sizes (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is pragma Unreferenced (Object); begin MAT.Commands.Sizes_Command (Target.all, ""); end On_Btn_Sizes; -- ------------------------------ -- Callback executed when the "cmd-threads" action is executed from the "Threads" action. -- ------------------------------ procedure On_Btn_Threads (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is pragma Unreferenced (Object); begin MAT.Commands.Threads_Command (Target.all, ""); end On_Btn_Threads; end MAT.Callbacks;
Implement the On_Btn_Threads procedure and register the callback
Implement the On_Btn_Threads procedure and register the callback
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
483efa19dcd1b9300b547474017d66336e224849
mat/src/memory/mat-memory.ads
mat/src/memory/mat-memory.ads
----------------------------------------------------------------------- -- Memory - Memory slot -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Frames; with Interfaces; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; -- Statistics about memory allocation. type Memory_Info is record Total_Size : MAT.Types.Target_Size := 0; Alloc_Count : Natural := 0; Min_Slot_Size : MAT.Types.Target_Size := 0; Max_Slot_Size : MAT.Types.Target_Size := 0; Min_Addr : MAT.Types.Target_Addr := 0; Max_Addr : MAT.Types.Target_Addr := 0; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; -- Define a map of <tt>Memory_Info</tt> keyed by the thread Id. -- Such map allows to give the list of threads and a summary of their allocation. use type MAT.Types.Target_Thread_Ref; package Memory_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref, Element_Type => Memory_Info); subtype Memory_Info_Map is Memory_Info_Maps.Map; subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor; type Frame_Info is record Thread : MAT.Types.Target_Thread_Ref; Memory : Memory_Info; end record; -- Define a map of <tt>Frame_Info</tt> keyed by the backtrace function address -- that performed the memory allocation directly or indirectly. package Frame_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Frame_Info); private end MAT.Memory;
----------------------------------------------------------------------- -- Memory - Memory slot -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Frames; with Interfaces; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; -- Statistics about memory allocation. type Memory_Info is record Total_Size : MAT.Types.Target_Size := 0; Alloc_Count : Natural := 0; Min_Slot_Size : MAT.Types.Target_Size := 0; Max_Slot_Size : MAT.Types.Target_Size := 0; Min_Addr : MAT.Types.Target_Addr := 0; Max_Addr : MAT.Types.Target_Addr := 0; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; -- Define a map of <tt>Memory_Info</tt> keyed by the thread Id. -- Such map allows to give the list of threads and a summary of their allocation. use type MAT.Types.Target_Thread_Ref; package Memory_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref, Element_Type => Memory_Info); subtype Memory_Info_Map is Memory_Info_Maps.Map; subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor; type Frame_Info is record Thread : MAT.Types.Target_Thread_Ref; Memory : Memory_Info; end record; -- Define a map of <tt>Frame_Info</tt> keyed by the backtrace function address -- that performed the memory allocation directly or indirectly. package Frame_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Frame_Info); subtype Frame_Info_Map is Frame_Info_Maps.Map; subtype Frame_Info_Cursor is Frame_Info_Maps.Cursor; private end MAT.Memory;
Define Frame_Info_Map and Frame_Info_Cursor subtypes
Define Frame_Info_Map and Frame_Info_Cursor subtypes
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
0d6151292d213c2497dc65216656207657c7a744
awa/plugins/awa-questions/src/awa-questions-modules.adb
awa/plugins/awa-questions/src/awa-questions-modules.adb
----------------------------------------------------------------------- -- awa-questions-modules -- Module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Questions.Beans; with AWA.Applications; package body AWA.Questions.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module"); package Register is new AWA.Modules.Beans (Module => Question_Module, Module_Access => Question_Module_Access); -- ------------------------------ -- Initialize the questions module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the questions module"); -- Setup the resource bundles. App.Register ("questionMsg", "questions"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Questions_Bean", Handler => AWA.Questions.Beans.Create_Question_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. Plugin.Manager := Plugin.Create_Question_Manager; end Initialize; -- ------------------------------ -- Get the question manager. -- ------------------------------ function Get_Question_Manager (Plugin : in Question_Module) return Services.Question_Service_Access is begin return Plugin.Manager; end Get_Question_Manager; -- ------------------------------ -- Create a question manager. This operation can be overridden to provide another -- question service implementation. -- ------------------------------ function Create_Question_Manager (Plugin : in Question_Module) return Services.Question_Service_Access is Result : constant Services.Question_Service_Access := new Services.Question_Service; begin Result.Initialize (Plugin); return Result; end Create_Question_Manager; -- ------------------------------ -- Get the questions module. -- ------------------------------ function Get_Question_Module return Question_Module_Access is function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME); begin return Get; end Get_Question_Module; end AWA.Questions.Modules;
----------------------------------------------------------------------- -- awa-questions-modules -- Module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Questions.Beans; with AWA.Applications; package body AWA.Questions.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module"); package Register is new AWA.Modules.Beans (Module => Question_Module, Module_Access => Question_Module_Access); -- ------------------------------ -- Initialize the questions module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the questions module"); -- Setup the resource bundles. App.Register ("questionMsg", "questions"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Questions_Bean", Handler => AWA.Questions.Beans.Create_Question_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. Plugin.Manager := Plugin.Create_Question_Manager; end Initialize; -- ------------------------------ -- Get the question manager. -- ------------------------------ function Get_Question_Manager (Plugin : in Question_Module) return Services.Question_Service_Access is begin return Plugin.Manager; end Get_Question_Manager; -- ------------------------------ -- Create a question manager. This operation can be overridden to provide another -- question service implementation. -- ------------------------------ function Create_Question_Manager (Plugin : in Question_Module) return Services.Question_Service_Access is Result : constant Services.Question_Service_Access := new Services.Question_Service; begin Result.Initialize (Plugin); return Result; end Create_Question_Manager; -- ------------------------------ -- Get the questions module. -- ------------------------------ function Get_Question_Module return Question_Module_Access is function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME); begin return Get; end Get_Question_Module; -- ------------------------------ -- Get the question manager instance associated with the current application. -- ------------------------------ function Get_Question_Manager return Services.Question_Service_Access is Module : constant Question_Module_Access := Get_Question_Module; begin if Module = null then Log.Error ("There is no active Question_Module"); return null; else return Module.Get_Question_Manager; end if; end Get_Question_Manager; end AWA.Questions.Modules;
Implement the new function Get_Question_Manager
Implement the new function Get_Question_Manager
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa
0a7080fdf6fbee2038d84e97f4043778e3b044b2
samples/import.adb
samples/import.adb
----------------------------------------------------------------------- -- import -- Import some HTML content and generate Wiki text -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Wide_Wide_Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with GNAT.Command_Line; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings.Transforms; with Wiki.Strings; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Render.Wiki; with Wiki.Documents; with Wiki.Parsers; procedure Import is use GNAT.Command_Line; use Ada.Strings.Unbounded; use Ada.Strings.UTF_Encoding; procedure Usage; function Is_Url (Name : in String) return Boolean; procedure Parse_Url (Url : in String); procedure Parse (Content : in String); procedure Print (Item : in Wiki.Strings.WString); Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Count : Natural := 0; Html_Mode : Boolean := True; Wiki_Mode : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; procedure Usage is begin Ada.Text_IO.Put_Line ("Import HTML into a target Wiki format"); Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-d] [-c] {URL | file}"); Ada.Text_IO.Put_Line (" -t Convert to text only"); Ada.Text_IO.Put_Line (" -m Convert to Markdown"); Ada.Text_IO.Put_Line (" -M Convert to Mediawiki"); Ada.Text_IO.Put_Line (" -d Convert to Dotclear"); Ada.Text_IO.Put_Line (" -c Convert to Creole"); end Usage; procedure Print (Item : in Wiki.Strings.WString) is begin Ada.Wide_Wide_Text_IO.Put (Item); end Print; procedure Parse (Content : in String) is Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); if Wiki_Mode then declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Engine.Set_Syntax (Wiki.SYNTAX_HTML); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access, Syntax); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; elsif Html_Mode then declare Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; else declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; end if; Ada.Wide_Wide_Text_IO.New_Line; end Parse; procedure Parse_Url (Url : in String) is Command : constant String := "wget -q -O - " & Url; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Pipe.Open (Command); Buffer.Initialize (Pipe'Unchecked_Access, 1024 * 1024); Buffer.Read (Content); Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Ada.Text_IO.Put_Line (Command & " exited with status " & Integer'Image (Pipe.Get_Exit_Status)); else Parse (To_String (Content)); end if; end Parse_Url; function Is_Url (Name : in String) return Boolean is begin if Name'Length <= 9 then return False; else return Name (Name'First .. Name'First + 6) = "http://" or Name (Name'First .. Name'First + 7) = "https://"; end if; end Is_Url; begin loop case Getopt ("m M d c t f:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; Wiki_Mode := True; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; Wiki_Mode := True; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; Wiki_Mode := True; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; Wiki_Mode := True; when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter); begin Html_Filter.Hide (Wiki.Html_Tag'Value (Value & "_TAG")); exception when Constraint_Error => Ada.Text_IO.Put_Line ("Invalid tag " & Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; if Is_Url (Name) then Parse_Url (Name); else Util.Files.Read_File (Name, Data); Parse (To_String (Data)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Import;
----------------------------------------------------------------------- -- import -- Import some HTML content and generate Wiki text -- Copyright (C) 2015, 2016, 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.Text_IO; with Ada.Wide_Wide_Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with GNAT.Command_Line; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings.Transforms; with Wiki.Strings; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Render.Wiki; with Wiki.Documents; with Wiki.Parsers; procedure Import is use GNAT.Command_Line; use Ada.Strings.Unbounded; use Ada.Strings.UTF_Encoding; procedure Usage; function Is_Url (Name : in String) return Boolean; procedure Parse_Url (Url : in String); procedure Parse (Content : in String); procedure Print (Item : in Wiki.Strings.WString); Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Count : Natural := 0; Html_Mode : Boolean := True; Wiki_Mode : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; procedure Usage is begin Ada.Text_IO.Put_Line ("Import HTML into a target Wiki format"); Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-H] [-d] [-c] {URL | file}"); Ada.Text_IO.Put_Line (" -t Convert to text only"); Ada.Text_IO.Put_Line (" -m Convert to Markdown"); Ada.Text_IO.Put_Line (" -M Convert to Mediawiki"); Ada.Text_IO.Put_Line (" -H Convert to HTML"); Ada.Text_IO.Put_Line (" -d Convert to Dotclear"); Ada.Text_IO.Put_Line (" -c Convert to Creole"); end Usage; procedure Print (Item : in Wiki.Strings.WString) is begin Ada.Wide_Wide_Text_IO.Put (Item); end Print; procedure Parse (Content : in String) is Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); if Wiki_Mode then declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Engine.Set_Syntax (Wiki.SYNTAX_HTML); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access, Syntax); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; elsif Html_Mode then declare Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; else declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; end if; Ada.Wide_Wide_Text_IO.New_Line; end Parse; procedure Parse_Url (Url : in String) is Command : constant String := "wget -q -O - " & Url; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Pipe.Open (Command); Buffer.Initialize (Pipe'Unchecked_Access, 1024 * 1024); Buffer.Read (Content); Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Ada.Text_IO.Put_Line (Command & " exited with status " & Integer'Image (Pipe.Get_Exit_Status)); else Parse (To_String (Content)); end if; end Parse_Url; function Is_Url (Name : in String) return Boolean is begin if Name'Length <= 9 then return False; else return Name (Name'First .. Name'First + 6) = "http://" or Name (Name'First .. Name'First + 7) = "https://"; end if; end Is_Url; begin loop case Getopt ("m M H d c t f:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; Wiki_Mode := True; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; Wiki_Mode := True; when 'H' => Syntax := Wiki.SYNTAX_HTML; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; Wiki_Mode := True; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; Wiki_Mode := True; when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter); begin Html_Filter.Hide (Wiki.Html_Tag'Value (Value & "_TAG")); exception when Constraint_Error => Ada.Text_IO.Put_Line ("Invalid tag " & Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; if Is_Url (Name) then Parse_Url (Name); else Util.Files.Read_File (Name, Data); Parse (To_String (Data)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Import;
Add -H option for HTML
Add -H option for HTML
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
4e20a8f368d61c178f530f30d7192d3b64c8fde7
awa/plugins/awa-storages/src/awa-storages-services.ads
awa/plugins/awa-storages/src/awa-storages-services.ads
----------------------------------------------------------------------- -- awa-storages-services -- Storage service -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; with Security.Permissions; with ADO; with ASF.Parts; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Storages.Models; with AWA.Storages.Stores; with AWA.Storages.Stores.Databases; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. -- -- @include awa-storages-stores.ads package AWA.Storages.Services is package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create"); type Read_Mode is (READ, WRITE); type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER); package Storage_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class); subtype Listener is Storage_Lifecycle.Listener; -- ------------------------------ -- Storage Service -- ------------------------------ -- The <b>Storage_Service</b> defines a set of operations to store and retrieve -- a data object from the persistent storage. The data object is treated as a raw -- byte stream. The persistent storage can be implemented by a database, a file -- system or a remote service such as Amazon AWS. type Storage_Service is new AWA.Modules.Module_Manager with private; type Storage_Service_Access is access all Storage_Service'Class; -- Initializes the storage service. overriding procedure Initialize (Service : in out Storage_Service; Module : in AWA.Modules.Module'Class); -- Get the persistent store that manages the data store identified by <tt>Kind</tt>. function Get_Store (Service : in Storage_Service; Kind : in AWA.Storages.Models.Storage_Type) return AWA.Storages.Stores.Store_Access; -- Create or save the folder. procedure Save_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class); -- Load the folder instance identified by the given identifier. procedure Load_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class; Id : in ADO.Identifier); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Data : in ASF.Parts.Part'Class; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file described <b>File</b> in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; File : in AWA.Storages.Storage_File; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file pointed to by the <b>Path</b> string in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String; Storage : in AWA.Storages.Models.Storage_Type); -- Load the storage instance identified by the given identifier. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Id : in ADO.Identifier); -- Load the storage instance stored in a folder and identified by a name. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Folder : in ADO.Identifier; Name : in String; Found : out Boolean); -- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>. -- Raises the <b>NOT_FOUND</b> exception if there is no such storage. procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); -- Load the storage content into a file. If the data is not stored in a file, a temporary -- file is created with the data content fetched from the store (ex: the database). -- The `Mode` parameter indicates whether the file will be read or written. -- The `Expire` parameter allows to control the expiration of the temporary file. procedure Get_Local_File (Service : in Storage_Service; From : in ADO.Identifier; Mode : in Read_Mode := READ; Into : out Storage_File); procedure Create_Local_File (Service : in out Storage_Service; Into : out AWA.Storages.Storage_File); -- Create a temporary file path. procedure Create_Local_File (Service : in out Storage_Service; Into : out AWA.Storages.Temporary_File); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in ADO.Identifier); private type Store_Access_Array is array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access; type Storage_Service is new AWA.Modules.Module_Manager with record Stores : Store_Access_Array; Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store; Temp_Id : Util.Concurrent.Counters.Counter; end record; end AWA.Storages.Services;
----------------------------------------------------------------------- -- awa-storages-services -- Storage service -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; with Security.Permissions; with ADO; with ASF.Parts; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Storages.Models; with AWA.Storages.Stores; with AWA.Storages.Stores.Databases; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. -- -- @include awa-storages-stores.ads package AWA.Storages.Services is package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create"); type Read_Mode is (READ, WRITE); type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER); package Storage_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class); subtype Listener is Storage_Lifecycle.Listener; -- ------------------------------ -- Storage Service -- ------------------------------ -- The <b>Storage_Service</b> defines a set of operations to store and retrieve -- a data object from the persistent storage. The data object is treated as a raw -- byte stream. The persistent storage can be implemented by a database, a file -- system or a remote service such as Amazon AWS. type Storage_Service is new AWA.Modules.Module_Manager with private; type Storage_Service_Access is access all Storage_Service'Class; -- Initializes the storage service. overriding procedure Initialize (Service : in out Storage_Service; Module : in AWA.Modules.Module'Class); -- Get the persistent store that manages the data store identified by <tt>Kind</tt>. function Get_Store (Service : in Storage_Service; Kind : in AWA.Storages.Models.Storage_Type) return AWA.Storages.Stores.Store_Access; -- Create or save the folder. procedure Save_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class); -- Load the folder instance identified by the given identifier. procedure Load_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class; Id : in ADO.Identifier); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Data : in ASF.Parts.Part'Class; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file described <b>File</b> in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; File : in AWA.Storages.Storage_File; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file pointed to by the <b>Path</b> string in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String; Storage : in AWA.Storages.Models.Storage_Type); -- Load the storage instance identified by the given identifier. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Id : in ADO.Identifier); -- Load the storage instance stored in a folder and identified by a name. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Folder : in ADO.Identifier; Name : in String; Found : out Boolean); -- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>. -- Raises the <b>NOT_FOUND</b> exception if there is no such storage. procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); -- Load the storage content into a file. If the data is not stored in a file, a temporary -- file is created with the data content fetched from the store (ex: the database). -- The `Mode` parameter indicates whether the file will be read or written. -- The `Expire` parameter allows to control the expiration of the temporary file. procedure Get_Local_File (Service : in Storage_Service; From : in ADO.Identifier; Mode : in Read_Mode := READ; Into : out Storage_File); procedure Create_Local_File (Service : in out Storage_Service; Into : in out AWA.Storages.Storage_File); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in ADO.Identifier); private type Store_Access_Array is array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access; type Storage_Service is new AWA.Modules.Module_Manager with record Stores : Store_Access_Array; Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store; Temp_Id : Util.Concurrent.Counters.Counter; end record; end AWA.Storages.Services;
Change Create_Local_File to use the Storage_File type
Change Create_Local_File to use the Storage_File type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d7f524075cb28b0501e7c81051ebadf0f7bcc754
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- 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 AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Wikis.Writers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with AWA.Wikis.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Wikis : aliased AWA.Wikis.Modules.Wiki_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Wikis.Writers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Register (App => Application.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => Wikis'Access); Application.Start; if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Wikis.Writers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Counters.Modules.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Counters.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with AWA.Wikis.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Wikis : aliased AWA.Wikis.Modules.Wiki_Module; Counters : aliased AWA.Counters.Modules.Counter_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Counters.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Wikis.Writers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Counters.Modules.NAME, URI => "counters", Module => Counters'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Register (App => Application.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => Wikis'Access); Application.Start; if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Add the unit tests for the AWA.Counters plugin
Add the unit tests for the AWA.Counters plugin
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
7fcd0e273e2137e45b098472b3d50f23e64dfa81
awa/src/awa-users-services.ads
awa/src/awa-users-services.ads
----------------------------------------------------------------------- -- awa.users -- User registration, authentication processes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Users.Models; with AWA.Users.Principals; with AWA.Modules; with AWA.Events; with Security.Auth; with Security.Random; with ADO; with ADO.Sessions; -- == Introduction == -- The *users* module provides a *users* service which controls the user data model. -- -- == Events == -- The *users* module exposes a number of events which are posted when some action -- are performed at the service level. -- -- === user-register === -- This event is posted when a new user is registered in the application. -- It can be used to send a registration email. -- -- === user-create === -- This event is posted when a new user is created. It can be used to trigger -- the pre-initialization of the application for the new user. -- -- === user-lost-password === -- This event is posted when a user asks for a password reset through an -- anonymous form. It is intended to be used to send the reset password email. -- -- === user-reset-password === -- This event is posted when a user has successfully reset his password. -- It can be used to send an email. -- package AWA.Users.Services is use AWA.Users.Models; package User_Create_Event is new AWA.Events.Definition (Name => "user-create"); package User_Register_Event is new AWA.Events.Definition (Name => "user-register"); package User_Lost_Password_Event is new AWA.Events.Definition (Name => "user-lost-password"); package User_Reset_Password_Event is new AWA.Events.Definition (Name => "user-reset-password"); NAME : constant String := "User_Service"; Not_Found : exception; User_Exist : exception; -- The session is an authenticate session. The user authenticated using password or OpenID. -- When the user logout, this session is closed as well as any connection session linked to -- the authenticate session. AUTH_SESSION_TYPE : constant Integer := 1; -- The session is a connection session. It is linked to an authenticate session. -- This session can be closed automatically due to a timeout or user's inactivity. -- The AID cookie refers to this connection session to create a new connection session. -- Once re-connecting is done, the connection session refered to by AID is marked -- as <b<USED_SESSION_TYPE</b> and a new AID cookie with the new connection session is -- returned to the user. CONNECT_SESSION_TYPE : constant Integer := 0; -- The session is a connection session whose associated AID cookie has been used. -- This session cannot be used to re-connect a user through the AID cookie. USED_SESSION_TYPE : constant Integer := 2; -- Get the user name from the email address. -- Returns the possible user name from his email address. function Get_Name_From_Email (Email : in String) return String; type User_Service is new AWA.Modules.Module_Manager with private; type User_Service_Access is access all User_Service'Class; -- Build the authenticate cookie. The cookie is signed using HMAC-SHA1 with a private key. function Get_Authenticate_Cookie (Model : in User_Service; Id : in ADO.Identifier) return String; -- Get the authenticate identifier from the cookie. -- Verify that the cookie is valid, the signature is correct. -- Returns the identified or NO_IDENTIFIER function Get_Authenticate_Id (Model : in User_Service; Cookie : in String) return ADO.Identifier; -- Get the password hash. The password is signed using HMAC-SHA1 with the salt. function Get_Password_Hash (Model : in User_Service; Password : in String; Salt : in String) return String; -- Create a user in the database with the given user information and -- the associated email address. Verify that no such user already exist. -- Raises User_Exist exception if a user with such email is already registered. procedure Create_User (Model : in out User_Service; User : in out User_Ref'Class; Email : in out Email_Ref'Class); -- Verify the access key and retrieve the user associated with that key. -- Starts a new session associated with the given IP address. -- The authenticated user is identified by a principal instance allocated -- and returned in <b>Principal</b>. -- Raises Not_Found if the access key does not exist. procedure Verify_User (Model : in User_Service; Key : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his email address and his password. -- If the user is authenticated, return the user information and -- create a new session. The IP address of the connection is saved -- in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Email : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his OpenID identifier. The authentication process -- was made by an external OpenID provider. If the user does not yet exists in -- the database, a record is created for him. Create a new session for the user. -- The IP address of the connection is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Auth : in Security.Auth.Authentication; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with the authenticate cookie generated from a previous authenticate -- session. If the cookie has the correct signature, matches a valid session, -- return the user information and create a new session. The IP address of the connection -- is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Cookie : in String; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Start the lost password process for a user. Find the user having -- the given email address and send that user a password reset key -- in an email. -- Raises Not_Found exception if no user with such email exist procedure Lost_Password (Model : in out User_Service; Email : in String); -- Reset the password of the user associated with the secure key. -- Raises Not_Found if there is no key or if the user does not have any email procedure Reset_Password (Model : in out User_Service; Key : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Verify that the user session identified by <b>Id</b> is valid and still active. -- Returns the user and the session objects. -- Raises Not_Found if the session does not exist or was closed. procedure Verify_Session (Model : in User_Service; Id : in ADO.Identifier; User : out User_Ref'Class; Session : out Session_Ref'Class); -- Closes the session identified by <b>Id</b>. The session identified should refer to -- a valid and not closed connection session. -- When <b>Logout</b> is set, the authenticate session is also closed. The connection -- sessions associated with the authenticate session are also closed. -- Raises <b>Not_Found</b> if the session is invalid or already closed. procedure Close_Session (Model : in User_Service; Id : in ADO.Identifier; Logout : in Boolean := False); -- Create and generate a new access key for the user. The access key is saved in the -- database and it will expire after the expiration delay. procedure Create_Access_Key (Model : in out User_Service; User : in AWA.Users.Models.User_Ref'Class; Key : in out AWA.Users.Models.Access_Key_Ref; Expire : in Duration; Session : in out ADO.Sessions.Master_Session); procedure Send_Alert (Model : in User_Service; Kind : in AWA.Events.Event_Index; User : in User_Ref'Class; Props : in out AWA.Events.Module_Event); -- Initialize the user service. overriding procedure Initialize (Model : in out User_Service; Module : in AWA.Modules.Module'Class); private function Create_Key (Model : in out User_Service; Number : in ADO.Identifier) return String; procedure Create_Session (Model : in User_Service; DB : in out ADO.Sessions.Master_Session; Session : out Session_Ref'Class; User : in User_Ref'Class; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); type User_Service is new AWA.Modules.Module_Manager with record Server_Id : Integer := 0; Random : Security.Random.Generator; Auth_Key : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Users.Services;
----------------------------------------------------------------------- -- awa.users -- User registration, authentication processes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Users.Models; with AWA.Users.Principals; with AWA.Modules; with AWA.Events; with Security.Auth; with Security.Random; with ADO; with ADO.Sessions; -- == Introduction == -- The *users* module provides a *users* service which controls the user data model. -- -- == Events == -- The *users* module exposes a number of events which are posted when some action -- are performed at the service level. -- -- === user-register === -- This event is posted when a new user is registered in the application. -- It can be used to send a registration email. -- -- === user-create === -- This event is posted when a new user is created. It can be used to trigger -- the pre-initialization of the application for the new user. -- -- === user-lost-password === -- This event is posted when a user asks for a password reset through an -- anonymous form. It is intended to be used to send the reset password email. -- -- === user-reset-password === -- This event is posted when a user has successfully reset his password. -- It can be used to send an email. -- package AWA.Users.Services is use AWA.Users.Models; package User_Create_Event is new AWA.Events.Definition (Name => "user-create"); package User_Register_Event is new AWA.Events.Definition (Name => "user-register"); package User_Lost_Password_Event is new AWA.Events.Definition (Name => "user-lost-password"); package User_Reset_Password_Event is new AWA.Events.Definition (Name => "user-reset-password"); NAME : constant String := "User_Service"; Not_Found : exception; User_Exist : exception; -- The session is an authenticate session. The user authenticated using password or OpenID. -- When the user logout, this session is closed as well as any connection session linked to -- the authenticate session. AUTH_SESSION_TYPE : constant Integer := 1; -- The session is a connection session. It is linked to an authenticate session. -- This session can be closed automatically due to a timeout or user's inactivity. -- The AID cookie refers to this connection session to create a new connection session. -- Once re-connecting is done, the connection session refered to by AID is marked -- as <b<USED_SESSION_TYPE</b> and a new AID cookie with the new connection session is -- returned to the user. CONNECT_SESSION_TYPE : constant Integer := 0; -- The session is a connection session whose associated AID cookie has been used. -- This session cannot be used to re-connect a user through the AID cookie. USED_SESSION_TYPE : constant Integer := 2; -- Get the user name from the email address. -- Returns the possible user name from his email address. function Get_Name_From_Email (Email : in String) return String; type User_Service is new AWA.Modules.Module_Manager with private; type User_Service_Access is access all User_Service'Class; -- Build the authenticate cookie. The cookie is signed using HMAC-SHA1 with a private key. function Get_Authenticate_Cookie (Model : in User_Service; Id : in ADO.Identifier) return String; -- Get the authenticate identifier from the cookie. -- Verify that the cookie is valid, the signature is correct. -- Returns the identified or NO_IDENTIFIER function Get_Authenticate_Id (Model : in User_Service; Cookie : in String) return ADO.Identifier; -- Get the password hash. The password is signed using HMAC-SHA1 with the salt. function Get_Password_Hash (Model : in User_Service; Password : in String; Salt : in String) return String; -- Create a user in the database with the given user information and -- the associated email address. Verify that no such user already exist. -- Raises User_Exist exception if a user with such email is already registered. procedure Create_User (Model : in out User_Service; User : in out User_Ref'Class; Email : in out Email_Ref'Class); -- Verify the access key and retrieve the user associated with that key. -- Starts a new session associated with the given IP address. -- The authenticated user is identified by a principal instance allocated -- and returned in <b>Principal</b>. -- Raises Not_Found if the access key does not exist. procedure Verify_User (Model : in User_Service; Key : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his email address and his password. -- If the user is authenticated, return the user information and -- create a new session. The IP address of the connection is saved -- in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Email : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his OpenID identifier. The authentication process -- was made by an external OpenID provider. If the user does not yet exists in -- the database, a record is created for him. Create a new session for the user. -- The IP address of the connection is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Auth : in Security.Auth.Authentication; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with the authenticate cookie generated from a previous authenticate -- session. If the cookie has the correct signature, matches a valid session, -- return the user information and create a new session. The IP address of the connection -- is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Cookie : in String; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Start the lost password process for a user. Find the user having -- the given email address and send that user a password reset key -- in an email. -- Raises Not_Found exception if no user with such email exist procedure Lost_Password (Model : in out User_Service; Email : in String); -- Reset the password of the user associated with the secure key. -- Raises Not_Found if there is no key or if the user does not have any email procedure Reset_Password (Model : in out User_Service; Key : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Verify that the user session identified by <b>Id</b> is valid and still active. -- Returns the user and the session objects. -- Raises Not_Found if the session does not exist or was closed. procedure Verify_Session (Model : in User_Service; Id : in ADO.Identifier; User : out User_Ref'Class; Session : out Session_Ref'Class); -- Closes the session identified by <b>Id</b>. The session identified should refer to -- a valid and not closed connection session. -- When <b>Logout</b> is set, the authenticate session is also closed. The connection -- sessions associated with the authenticate session are also closed. -- Raises <b>Not_Found</b> if the session is invalid or already closed. procedure Close_Session (Model : in User_Service; Id : in ADO.Identifier; Logout : in Boolean := False); -- Create and generate a new access key for the user. The access key is saved in the -- database and it will expire after the expiration delay. procedure Create_Access_Key (Model : in out User_Service; User : in AWA.Users.Models.User_Ref'Class; Key : in out AWA.Users.Models.Access_Key_Ref; Kind : in AWA.Users.Models.Key_Type; Expire : in Duration; Session : in out ADO.Sessions.Master_Session); procedure Send_Alert (Model : in User_Service; Kind : in AWA.Events.Event_Index; User : in User_Ref'Class; Props : in out AWA.Events.Module_Event); -- Initialize the user service. overriding procedure Initialize (Model : in out User_Service; Module : in AWA.Modules.Module'Class); private function Create_Key (Model : in out User_Service; Number : in ADO.Identifier) return String; procedure Create_Session (Model : in User_Service; DB : in out ADO.Sessions.Master_Session; Session : out Session_Ref'Class; User : in User_Ref'Class; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); type User_Service is new AWA.Modules.Module_Manager with record Server_Id : Integer := 0; Random : Security.Random.Generator; Auth_Key : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Users.Services;
Add the Kind : in AWA.Users.Models.Key_Type; parameter to the Create_Access_Key operation
Add the Kind : in AWA.Users.Models.Key_Type; parameter to the Create_Access_Key operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
dd468acf8956db5c6986615d353134b6c405e66f
examples/userdata_example.adb
examples/userdata_example.adb
-- Userdata_Example -- A example of using the Ada values in Lua via UserData values -- Copyright (c) 2015, James Humphry - see LICENSE for terms with Ada.Text_IO; use Ada.Text_IO; with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO; with Lua; use Lua; with Lua.Util; use Lua.Util; with Example_Userdata; use Example_Userdata; procedure Userdata_Example is L : Lua_State; Result : Boolean; Counter : Integer; Discard :Thread_Status; Example_Object : aliased Parent := (Flag => True); Child_Object : aliased Child := (Counter => 3, Flag => False); begin Put_Line("Using Ada values as userdata in Lua"); Put("Lua version: "); Put(Item => L.Version, Aft => 0, Exp => 0); New_Line;New_Line; Put_Line("There are three Ada types, Grandparent(abstract)->Parent->Child"); Put_Line("Grandparent and descendants have a flag that can be toggled"); Put_Line("Child has a counter that can be incremented"); Put_Line("There are only two userdata types in Lua, Grandparent and Child."); New_Line; -- Register the "toggle" and "increment" operations in the metatables. Register_Operations(L); Put_Line("Pushing an 'Parent' value (Flag => True) to the stack as an Grandparent'Class userdata."); Grandparent_Userdata.Push_Class(L, Example_Object'Unchecked_Access); Put_Line("Saving a copy of the userdata in global variable 'foo'"); L.PushValue(-1); L.SetGlobal("foo"); Print_Stack(L); Put_Line("Retrieving the value of 'Flag' from the value at the top of the stack."); Result := Grandparent_Userdata.ToUserdata(L, -1).Flag; Put_Line((if Result then "Foo.Flag is now true" else "Foo.Flag is now false")); New_Line; Put_Line("Pushing an 'Child' value (Counter => 3, Flag => False) to the stack as an Child userdata."); Child_Userdata.Push(L, Child_Object'Unchecked_Access); Print_Stack(L); Put_Line("Saving the userdata at the top of the stack in global variable 'bar'"); L.SetGlobal("bar"); New_Line; Put_Line("Clearing the stack"); L.SetTop(0); New_Line; Put_Line("Calling 'foo:toggle()' in Lua"); Discard := L.LoadString_By_Copy("foo:toggle()"); L.Call(nargs => 0, nresults => 0); New_Line; Put_Line("Calling 'bar:toggle()' in Lua"); Discard := L.LoadString_By_Copy("bar:toggle()"); L.Call(nargs => 0, nresults => 0); New_Line; Put_Line("Calling 'bar:increment()' in Lua"); Discard := L.LoadString_By_Copy("bar:increment()"); L.Call(nargs => 0, nresults => 0); New_Line; New_Line; Put_Line("Retrieving the value of 'Flag' from foo and bar, treating them as Grandparent values."); L.GetGlobal("foo"); Result := Grandparent_Userdata.ToUserdata(L, -1).Flag; Put_Line((if Result then "foo.Flag is now true" else "foo.Flag is now false")); L.SetTop(0); L.GetGlobal("bar"); Result := Grandparent_Userdata.ToUserdata(L, -1).Flag; Put_Line((if Result then "bar.Flag is now true" else "bar.Flag is now false")); Put_Line("Retrieving the value of 'Counter' from bar, treating it as an Child value."); Counter := Child_Userdata.ToUserdata(L, -1).Counter; Put_Line("bar.Counter = " & Integer'Image(Counter)); New_Line; end Userdata_Example;
-- Userdata_Example -- A example of using the Ada values in Lua via UserData values -- Copyright (c) 2015, James Humphry - see LICENSE for terms with Ada.Text_IO; use Ada.Text_IO; with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO; with Lua; use Lua; with Lua.Util; use Lua.Util; with Example_Userdata; use Example_Userdata; procedure Userdata_Example is L : Lua_State; Result : Boolean; Counter : Integer; Discard :Thread_Status; Parent_Object : aliased Parent := (Flag => True); Child_Object : aliased Child := (Counter => 3, Flag => False); begin Put_Line("Using Ada values as userdata in Lua"); Put("Lua version: "); Put(Item => L.Version, Aft => 0, Exp => 0); New_Line;New_Line; Put_Line("There are three Ada types, Grandparent(abstract)->Parent->Child"); Put_Line("Grandparent and descendants have a flag that can be toggled"); Put_Line("Child has a counter that can be incremented"); Put_Line("There are only two userdata types in Lua, Grandparent and Child."); New_Line; -- Register the "toggle" and "increment" operations in the metatables. Register_Operations(L); Put_Line("Pushing an 'Parent' value (Flag => True) to the stack as a Grandparent'Class userdata."); Grandparent_Userdata.Push_Class(L, Parent_Object'Unchecked_Access); Put_Line("Saving a copy of the userdata in global variable 'parent_foo'"); L.PushValue(-1); L.SetGlobal("parent_foo"); Print_Stack(L); Put_Line("Retrieving the value of 'Flag' from the value at the top of the stack."); Result := Grandparent_Userdata.ToUserdata(L, -1).Flag; Put_Line((if Result then "parent_foo.Flag is now true" else "parent_foo.Flag is now false")); New_Line; Put_Line("Pushing an 'Child' value (Counter => 3, Flag => False) to the stack as a Child userdata."); Child_Userdata.Push(L, Child_Object'Unchecked_Access); Print_Stack(L); Put_Line("Saving the userdata at the top of the stack in global variable 'child_bar'"); L.SetGlobal("child_bar"); New_Line; Put_Line("Clearing the stack"); L.SetTop(0); New_Line; Put_Line("Calling 'parent_foo:toggle()' in Lua"); Discard := L.LoadString_By_Copy("parent_foo:toggle()"); L.Call(nargs => 0, nresults => 0); New_Line; Put_Line("Calling 'child_bar:toggle()' in Lua"); Discard := L.LoadString_By_Copy("child_bar:toggle()"); L.Call(nargs => 0, nresults => 0); New_Line; Put_Line("Calling 'child_bar:increment()' in Lua"); Discard := L.LoadString_By_Copy("child_bar:increment()"); L.Call(nargs => 0, nresults => 0); New_Line; New_Line; Put_Line("Retrieving the value of 'Flag' from parent_foo and child_bar, " & "treating them as Grandparent values."); L.GetGlobal("parent_foo"); Result := Grandparent_Userdata.ToUserdata(L, -1).Flag; Put_Line((if Result then "parent_foo.Flag is now true" else "parent_foo.Flag is now false")); L.SetTop(0); L.GetGlobal("child_bar"); Result := Grandparent_Userdata.ToUserdata(L, -1).Flag; Put_Line((if Result then "child_bar.Flag is now true" else "child_bar.Flag is now false")); Put_Line("Retrieving the value of 'Counter' from child_bar, " & "treating it as a Child value."); Counter := Child_Userdata.ToUserdata(L, -1).Counter; Put_Line("child_bar.Counter = " & Integer'Image(Counter)); New_Line; end Userdata_Example;
Clarify parts of userdata_example.adb
Clarify parts of userdata_example.adb Hopefully it is a little clearer now.
Ada
mit
jhumphry/aLua
f40f5ae94e4b8c9be80b39f27317981bf78ead3d
awa/plugins/awa-comments/src/awa-comments-modules.adb
awa/plugins/awa-comments/src/awa-comments-modules.adb
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Sessions; with ADO.Sessions.Entities; with Security.Permissions; with AWA.Users.Models; with AWA.Permissions; with AWA.Modules.Beans; with AWA.Services.Contexts; with AWA.Comments.Beans; package body AWA.Comments.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module"); package Register is new AWA.Modules.Beans (Module => Comment_Module, Module_Access => Comment_Module_Access); -- ------------------------------ -- Initialize the comments module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the comments module"); -- Setup the resource bundles. App.Register ("commentMsg", "comments"); -- Register the comment list bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_List_Bean", Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access); -- Register the comment bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_Bean", Handler => AWA.Comments.Beans.Create_Comment_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Load the comment identified by the given identifier. -- ------------------------------ procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Comment.Load (DB, Id, Found); end Load_Comment; -- ------------------------------ -- Create a new comment for the associated database entity. -- ------------------------------ procedure Create_Comment (Model : in Comment_Module; Permission : in String; Entity_Type : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment.Get_Entity_Id); Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type)); Comment.Set_Author (User); Comment.Set_Create_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; end Create_Comment; -- ------------------------------ -- Update the comment represented by <tt>Comment</tt> if the current user has the -- permission identified by <tt>Permission</tt>. -- ------------------------------ procedure Update_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin if not Comment.Is_Inserted then Log.Error ("The comment was not created"); raise Not_Found with "The comment was not inserted"; end if; Ctx.Start; Log.Info ("Updating the comment {0}", ADO.Identifier'Image (Comment.Get_Id)); -- Check that the user has the update permission on the given comment. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment); Comment.Save (DB); Ctx.Commit; end Update_Comment; -- ------------------------------ -- Delete the comment represented by <tt>Comment</tt> if the current user has the -- permission identified by <tt>Permission</tt>. -- ------------------------------ procedure Delete_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; -- Check that the user has the delete permission on the given answer. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment); Comment.Delete (DB); Ctx.Commit; end Delete_Comment; end AWA.Comments.Modules;
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Sessions; with ADO.Sessions.Entities; with Security.Permissions; with AWA.Users.Models; with AWA.Permissions; with AWA.Modules.Beans; with AWA.Services.Contexts; with AWA.Comments.Beans; package body AWA.Comments.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module"); package Register is new AWA.Modules.Beans (Module => Comment_Module, Module_Access => Comment_Module_Access); -- ------------------------------ -- Initialize the comments module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the comments module"); -- Setup the resource bundles. App.Register ("commentMsg", "comments"); -- Register the comment list bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_List_Bean", Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access); -- Register the comment bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_Bean", Handler => AWA.Comments.Beans.Create_Comment_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Load the comment identified by the given identifier. -- ------------------------------ procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Comment.Load (DB, Id, Found); end Load_Comment; -- ------------------------------ -- Create a new comment for the associated database entity. -- ------------------------------ procedure Create_Comment (Model : in Comment_Module; Permission : in String; Entity_Type : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment.Get_Entity_Id); Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type)); Comment.Set_Author (User); Comment.Set_Create_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; end Create_Comment; -- ------------------------------ -- Update the comment represented by <tt>Comment</tt> if the current user has the -- permission identified by <tt>Permission</tt>. -- ------------------------------ procedure Update_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin if not Comment.Is_Inserted then Log.Error ("The comment was not created"); raise Not_Found with "The comment was not inserted"; end if; Ctx.Start; Log.Info ("Updating the comment {0}", ADO.Identifier'Image (Comment.Get_Id)); -- Check that the user has the update permission on the given comment. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment); Comment.Save (DB); Ctx.Commit; end Update_Comment; -- ------------------------------ -- Delete the comment represented by <tt>Comment</tt> if the current user has the -- permission identified by <tt>Permission</tt>. -- ------------------------------ procedure Delete_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; -- Check that the user has the delete permission on the given answer. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment); Comment.Delete (DB); Ctx.Commit; end Delete_Comment; -- ------------------------------ -- Set the publication status of the comment represented by <tt>Comment</tt> -- if the current user has the permission identified by <tt>Permission</tt>. -- ------------------------------ procedure Publish_Comment (Model : in Comment_Module; Permission : in String; Id : in ADO.Identifier; Status : in AWA.Comments.Models.Status_Type; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; -- Check that the user has the permission to publish for the given comment. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Id); Comment.Load (DB, Id); Comment.Set_Status (Status); Comment.Save (DB); Ctx.Commit; end Publish_Comment; end AWA.Comments.Modules;
Implement the Publish_Comment operation, check the permission, load the comment, change the status and return the comment instance
Implement the Publish_Comment operation, check the permission, load the comment, change the status and return the comment instance
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2d9ddeed5e07996e685c9005e8afe6c4cc3d077e
awa/plugins/awa-questions/src/awa-questions-beans.adb
awa/plugins/awa-questions/src/awa-questions-beans.adb
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with Util.Beans.Lists.Strings; with AWA.Tags.Modules; with AWA.Services.Contexts; package body AWA.Questions.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tags" then return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Service.Load_Question (From, Id); From.Tags.Load_Tags (DB, Id); end; end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Question (Bean); Bean.Tags.Update_Tags (Bean.Get_Id); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); Object.Tags.Set_Permission ("question-edit"); return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Answer (From, From.Question, ADO.Utils.To_Identifier (Value)); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Answer (Answer => Bean); end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_List_Bean; Name : in String) return Util.Beans.Objects.Object is Pos : Natural; begin if Name = "tags" then Pos := From.Questions.Get_Row_Index; if Pos = 0 then return Util.Beans.Objects.Null_Object; end if; declare Item : constant Models.Question_Info := From.Questions.List.Element (Pos - 1); begin return From.Tags.Get_Tags (Item.Id); end; elsif Name = "questions" then return Util.Beans.Objects.To_Object (Value => From.Questions_Bean, Storage => Util.Beans.Objects.STATIC); else return From.Questions.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "tag" then From.Tag := Util.Beans.Objects.To_Unbounded_String (Value); From.Load_List; end if; end Set_Value; -- ------------------------------ -- Load the list of question. If a tag was set, filter the list of questions with the tag. -- ------------------------------ procedure Load_List (Into : in out Question_List_Bean) is use AWA.Questions.Models; use AWA.Services; use type ADO.Identifier; Session : ADO.Sessions.Session := Into.Service.Get_Session; Query : ADO.Queries.Context; Tag_Id : ADO.Identifier; begin AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id); if Tag_Id /= ADO.NO_IDENTIFIER then Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List); Query.Bind_Param (Name => "tag", Value => Tag_Id); else Query.Set_Query (AWA.Questions.Models.Query_Question_List); end if; ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Into.Questions, Session, Query); declare List : ADO.Utils.Identifier_Vector; Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First; begin while Question_Info_Vectors.Has_Element (Iter) loop List.Append (Question_Info_Vectors.Element (Iter).Id); Question_Info_Vectors.Next (Iter); end loop; Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all, List); end; end Load_List; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_List_Bean_Access := new Question_List_Bean; -- Session : ADO.Sessions.Session := Module.Get_Session; -- Query : ADO.Queries.Context; begin Object.Service := Module; Object.Questions_Bean := Object.Questions'Unchecked_Access; -- Query.Set_Query (AWA.Questions.Models.Query_Question_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "entity_type", -- Table => AWA.Questions.Models.QUESTION_TABLE, -- Session => Session); -- AWA.Questions.Models.List (Object.Questions, Session, Query); Object.Load_List; return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "tags" then return Util.Beans.Objects.To_Object (Value => From.Tags_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare package ASC renames AWA.Services.Contexts; use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; Ctx : constant ASC.Service_Context_Access := ASC.Current; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Id); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.ANSWER_TABLE, Session => Session); Query.Set_Query (AWA.Questions.Models.Query_Answer_List); AWA.Questions.Models.List (From.Answer_List, Session, Query); -- Load the tags if any. From.Tags.Load_Tags (Session, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with Util.Beans.Lists.Strings; with AWA.Tags.Modules; with AWA.Services.Contexts; package body AWA.Questions.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tags" then return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Service.Load_Question (From, Id); From.Tags.Load_Tags (DB, Id); end; end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Question (Bean); Bean.Tags.Update_Tags (Bean.Get_Id); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); Object.Tags.Set_Permission ("question-edit"); return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Answer (From, From.Question, ADO.Utils.To_Identifier (Value)); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Answer (Answer => Bean); end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_List_Bean; Name : in String) return Util.Beans.Objects.Object is Pos : Natural; begin if Name = "tags" then Pos := From.Questions.Get_Row_Index; if Pos = 0 then return Util.Beans.Objects.Null_Object; end if; declare Item : constant Models.Question_Info := From.Questions.List.Element (Pos - 1); begin return From.Tags.Get_Tags (Item.Id); end; elsif Name = "questions" then return Util.Beans.Objects.To_Object (Value => From.Questions_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "tag" then return Util.Beans.Objects.To_Object (From.Tag); else return From.Questions.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "tag" then From.Tag := Util.Beans.Objects.To_Unbounded_String (Value); From.Load_List; end if; end Set_Value; -- ------------------------------ -- Load the list of question. If a tag was set, filter the list of questions with the tag. -- ------------------------------ procedure Load_List (Into : in out Question_List_Bean) is use AWA.Questions.Models; use AWA.Services; use type ADO.Identifier; Session : ADO.Sessions.Session := Into.Service.Get_Session; Query : ADO.Queries.Context; Tag_Id : ADO.Identifier; begin AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id); if Tag_Id /= ADO.NO_IDENTIFIER then Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List); Query.Bind_Param (Name => "tag", Value => Tag_Id); else Query.Set_Query (AWA.Questions.Models.Query_Question_List); end if; ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Into.Questions, Session, Query); declare List : ADO.Utils.Identifier_Vector; Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First; begin while Question_Info_Vectors.Has_Element (Iter) loop List.Append (Question_Info_Vectors.Element (Iter).Id); Question_Info_Vectors.Next (Iter); end loop; Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all, List); end; end Load_List; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_List_Bean_Access := new Question_List_Bean; -- Session : ADO.Sessions.Session := Module.Get_Session; -- Query : ADO.Queries.Context; begin Object.Service := Module; Object.Questions_Bean := Object.Questions'Unchecked_Access; -- Query.Set_Query (AWA.Questions.Models.Query_Question_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "entity_type", -- Table => AWA.Questions.Models.QUESTION_TABLE, -- Session => Session); -- AWA.Questions.Models.List (Object.Questions, Session, Query); Object.Load_List; return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "tags" then return Util.Beans.Objects.To_Object (Value => From.Tags_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare package ASC renames AWA.Services.Contexts; use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; Ctx : constant ASC.Service_Context_Access := ASC.Current; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Id); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.ANSWER_TABLE, Session => Session); Query.Set_Query (AWA.Questions.Models.Query_Answer_List); AWA.Questions.Models.List (From.Answer_List, Session, Query); -- Load the tags if any. From.Tags.Load_Tags (Session, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
Make the current tag value visible to the question list bean
Make the current tag value visible to the question list bean
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
40c13dafbd704260a528326a1259520a7b347b3e
samples/mapping.adb
samples/mapping.adb
----------------------------------------------------------------------- -- mapping -- Example of serialization mappings -- 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 Util.Http.Clients; with Util.Http.Clients.Web; with Util.Serialize.IO.JSON; package body Mapping is use Util.Beans.Objects; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Mapping"); procedure Rest_Get (URI : in String; Mapping : in Util.Serialize.Mappers.Mapper_Access; Into : in Element_Type_Access) is Http : Util.Http.Clients.Client; Reader : Util.Serialize.IO.JSON.Parser; Response : Util.Http.Clients.Response; begin Reader.Add_Mapping ("", Mapping); Set_Context (Reader, Into); Http.Get (URI, Response); declare Content : constant String := Response.Get_Body; begin Reader.Parse_String (Content); end; end Rest_Get; type Property_Fields is (FIELD_NAME, FIELD_VALUE); type Property_Access is access all Property; type Address_Fields is (FIELD_CITY, FIELD_STREET, FIELD_COUNTRY, FIELD_ZIP); type Address_Access is access all Address; procedure Proxy_Address (Attr : in Util.Serialize.Mappers.Mapping'Class; Element : in out Person; Value : in Util.Beans.Objects.Object); function Get_Address_Member (Addr : in Address; Field : in Address_Fields) return Util.Beans.Objects.Object; procedure Set_Member (Addr : in out Address; Field : in Address_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Property; Field : in Property_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Property; Field : in Property_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => P.Name := To_Unbounded_String (Value); when FIELD_VALUE => P.Value := To_Unbounded_String (Value); end case; end Set_Member; package Property_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Property, Element_Type_Access => Property_Access, Fields => Property_Fields, Set_Member => Set_Member); -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ procedure Set_Member (P : in out Person; Field : in Person_Fields; Value : in Util.Beans.Objects.Object) is begin Log.Debug ("Person field {0} - {0}", Person_Fields'Image (Field), To_String (Value)); case Field is when FIELD_FIRST_NAME => P.First_Name := To_Unbounded_String (Value); when FIELD_LAST_NAME => P.Last_Name := To_Unbounded_String (Value); when FIELD_AGE => P.Age := To_Integer (Value); when FIELD_ID => P.Id := To_Long_Long_Integer (Value); when FIELD_NAME => P.Name := To_Unbounded_String (Value); when FIELD_USER_NAME => P.Username := To_Unbounded_String (Value); when FIELD_GENDER => P.Gender := To_Unbounded_String (Value); when FIELD_LINK => P.Link := To_Unbounded_String (Value); end case; end Set_Member; -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ function Get_Person_Member (From : in Person; Field : in Person_Fields) return Util.Beans.Objects.Object is begin case Field is when FIELD_FIRST_NAME => return Util.Beans.Objects.To_Object (From.First_Name); when FIELD_LAST_NAME => return Util.Beans.Objects.To_Object (From.Last_Name); when FIELD_AGE => return Util.Beans.Objects.To_Object (From.Age); when FIELD_NAME => return Util.Beans.Objects.To_Object (From.Name); when FIELD_USER_NAME => return Util.Beans.Objects.To_Object (From.Username); when FIELD_LINK => return Util.Beans.Objects.To_Object (From.Link); when FIELD_GENDER => return Util.Beans.Objects.To_Object (From.Gender); when FIELD_ID => return Util.Beans.Objects.To_Object (From.Id); end case; end Get_Person_Member; -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ procedure Set_Member (Addr : in out Address; Field : in Address_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CITY => Addr.City := To_Unbounded_String (Value); when FIELD_STREET => Addr.Street := To_Unbounded_String (Value); when FIELD_COUNTRY => Addr.Country := To_Unbounded_String (Value); when FIELD_ZIP => Addr.Zip := To_Integer (Value); end case; end Set_Member; function Get_Address_Member (Addr : in Address; Field : in Address_Fields) return Util.Beans.Objects.Object is begin case Field is when FIELD_CITY => return Util.Beans.Objects.To_Object (Addr.City); when FIELD_STREET => return Util.Beans.Objects.To_Object (Addr.Street); when FIELD_COUNTRY => return Util.Beans.Objects.To_Object (Addr.Country); when FIELD_ZIP => return Util.Beans.Objects.To_Object (Addr.Zip); end case; end Get_Address_Member; package Address_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Address, Element_Type_Access => Address_Access, Fields => Address_Fields, Set_Member => Set_Member); -- Mapping for the Property record. Property_Mapping : aliased Property_Mapper.Mapper; -- Mapping for the Address record. Address_Mapping : aliased Address_Mapper.Mapper; -- Mapping for the Person record. Person_Mapping : aliased Person_Mapper.Mapper; -- Mapping for a list of Person records (stored as a Vector). Person_Vector_Mapping : aliased Person_Vector_Mapper.Mapper; -- ------------------------------ -- Get the address mapper which describes how to load an Address. -- ------------------------------ function Get_Address_Mapper return Util.Serialize.Mappers.Mapper_Access is begin return Address_Mapping'Access; end Get_Address_Mapper; -- ------------------------------ -- Get the person mapper which describes how to load a Person. -- ------------------------------ function Get_Person_Mapper return Person_Mapper.Mapper_Access is begin return Person_Mapping'Access; end Get_Person_Mapper; -- ------------------------------ -- Get the person vector mapper which describes how to load a list of Person. -- ------------------------------ function Get_Person_Vector_Mapper return Person_Vector_Mapper.Mapper_Access is begin return Person_Vector_Mapping'Access; end Get_Person_Vector_Mapper; -- ------------------------------ -- Helper to give access to the <b>Address</b> member of a <b>Person</b>. -- ------------------------------ procedure Proxy_Address (Attr : in Util.Serialize.Mappers.Mapping'Class; Element : in out Person; Value : in Util.Beans.Objects.Object) is begin Address_Mapper.Set_Member (Attr, Element.Addr, Value); end Proxy_Address; begin Property_Mapping.Add_Default_Mapping; -- XML: JSON: -- ---- ----- -- <city>Paris</city> "city" : "Paris" -- <street>Champs de Mars</street> "street" : "Champs de Mars" -- <country>France</country> "country" : "France" -- <zip>75</zip> "zip" : 75 Address_Mapping.Bind (Get_Address_Member'Access); -- Address_Mapping.Add_Mapping ("info", Property_Mapping'Access, Proxy_Info'Access); Address_Mapping.Add_Default_Mapping; -- XML: -- ---- -- <xxx id='23'> -- <address> -- <city>...</city> -- <street number='44'>..</street> -- <country>..</country> -- <zip>..</zip> -- </address> -- <name>John</name> -- <last_name>Harry</last_name> -- <age>23</age> -- <info><facebook><id>...</id></facebook></info> -- </xxx> -- Person_Mapper.Add_Mapping ("@id"); Person_Mapping.Bind (Get_Person_Member'Access); Person_Mapping.Add_Mapping ("address", Address_Mapping'Access, Proxy_Address'Access); Person_Mapping.Add_Default_Mapping; -- Person_Mapper.Add_Mapping ("info/*"); -- Person_Mapper.Add_Mapping ("address/street/@number"); Person_Vector_Mapping.Set_Mapping (Person_Mapping'Access); end Mapping;
----------------------------------------------------------------------- -- mapping -- Example of serialization mappings -- 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 Util.Http.Clients; with Util.Http.Clients.Web; with Util.Serialize.IO.JSON; with Util.Http.Rest; package body Mapping is use Util.Beans.Objects; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Mapping"); procedure Rest_Get (URI : in String; Mapping : in Util.Serialize.Mappers.Mapper_Access; Into : in Element_Type_Access) is Http : Util.Http.Rest.Client; Reader : Util.Serialize.IO.JSON.Parser; begin Reader.Add_Mapping ("", Mapping); Set_Context (Reader, Into); Http.Get (URI, Reader); end Rest_Get; type Property_Fields is (FIELD_NAME, FIELD_VALUE); type Property_Access is access all Property; type Address_Fields is (FIELD_CITY, FIELD_STREET, FIELD_COUNTRY, FIELD_ZIP); type Address_Access is access all Address; procedure Proxy_Address (Attr : in Util.Serialize.Mappers.Mapping'Class; Element : in out Person; Value : in Util.Beans.Objects.Object); function Get_Address_Member (Addr : in Address; Field : in Address_Fields) return Util.Beans.Objects.Object; procedure Set_Member (Addr : in out Address; Field : in Address_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Property; Field : in Property_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Property; Field : in Property_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => P.Name := To_Unbounded_String (Value); when FIELD_VALUE => P.Value := To_Unbounded_String (Value); end case; end Set_Member; package Property_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Property, Element_Type_Access => Property_Access, Fields => Property_Fields, Set_Member => Set_Member); -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ procedure Set_Member (P : in out Person; Field : in Person_Fields; Value : in Util.Beans.Objects.Object) is begin Log.Debug ("Person field {0} - {0}", Person_Fields'Image (Field), To_String (Value)); case Field is when FIELD_FIRST_NAME => P.First_Name := To_Unbounded_String (Value); when FIELD_LAST_NAME => P.Last_Name := To_Unbounded_String (Value); when FIELD_AGE => P.Age := To_Integer (Value); when FIELD_ID => P.Id := To_Long_Long_Integer (Value); when FIELD_NAME => P.Name := To_Unbounded_String (Value); when FIELD_USER_NAME => P.Username := To_Unbounded_String (Value); when FIELD_GENDER => P.Gender := To_Unbounded_String (Value); when FIELD_LINK => P.Link := To_Unbounded_String (Value); end case; end Set_Member; -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ function Get_Person_Member (From : in Person; Field : in Person_Fields) return Util.Beans.Objects.Object is begin case Field is when FIELD_FIRST_NAME => return Util.Beans.Objects.To_Object (From.First_Name); when FIELD_LAST_NAME => return Util.Beans.Objects.To_Object (From.Last_Name); when FIELD_AGE => return Util.Beans.Objects.To_Object (From.Age); when FIELD_NAME => return Util.Beans.Objects.To_Object (From.Name); when FIELD_USER_NAME => return Util.Beans.Objects.To_Object (From.Username); when FIELD_LINK => return Util.Beans.Objects.To_Object (From.Link); when FIELD_GENDER => return Util.Beans.Objects.To_Object (From.Gender); when FIELD_ID => return Util.Beans.Objects.To_Object (From.Id); end case; end Get_Person_Member; -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ procedure Set_Member (Addr : in out Address; Field : in Address_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CITY => Addr.City := To_Unbounded_String (Value); when FIELD_STREET => Addr.Street := To_Unbounded_String (Value); when FIELD_COUNTRY => Addr.Country := To_Unbounded_String (Value); when FIELD_ZIP => Addr.Zip := To_Integer (Value); end case; end Set_Member; function Get_Address_Member (Addr : in Address; Field : in Address_Fields) return Util.Beans.Objects.Object is begin case Field is when FIELD_CITY => return Util.Beans.Objects.To_Object (Addr.City); when FIELD_STREET => return Util.Beans.Objects.To_Object (Addr.Street); when FIELD_COUNTRY => return Util.Beans.Objects.To_Object (Addr.Country); when FIELD_ZIP => return Util.Beans.Objects.To_Object (Addr.Zip); end case; end Get_Address_Member; package Address_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Address, Element_Type_Access => Address_Access, Fields => Address_Fields, Set_Member => Set_Member); -- Mapping for the Property record. Property_Mapping : aliased Property_Mapper.Mapper; -- Mapping for the Address record. Address_Mapping : aliased Address_Mapper.Mapper; -- Mapping for the Person record. Person_Mapping : aliased Person_Mapper.Mapper; -- Mapping for a list of Person records (stored as a Vector). Person_Vector_Mapping : aliased Person_Vector_Mapper.Mapper; -- ------------------------------ -- Get the address mapper which describes how to load an Address. -- ------------------------------ function Get_Address_Mapper return Util.Serialize.Mappers.Mapper_Access is begin return Address_Mapping'Access; end Get_Address_Mapper; -- ------------------------------ -- Get the person mapper which describes how to load a Person. -- ------------------------------ function Get_Person_Mapper return Person_Mapper.Mapper_Access is begin return Person_Mapping'Access; end Get_Person_Mapper; -- ------------------------------ -- Get the person vector mapper which describes how to load a list of Person. -- ------------------------------ function Get_Person_Vector_Mapper return Person_Vector_Mapper.Mapper_Access is begin return Person_Vector_Mapping'Access; end Get_Person_Vector_Mapper; -- ------------------------------ -- Helper to give access to the <b>Address</b> member of a <b>Person</b>. -- ------------------------------ procedure Proxy_Address (Attr : in Util.Serialize.Mappers.Mapping'Class; Element : in out Person; Value : in Util.Beans.Objects.Object) is begin Address_Mapper.Set_Member (Attr, Element.Addr, Value); end Proxy_Address; begin Property_Mapping.Add_Default_Mapping; -- XML: JSON: -- ---- ----- -- <city>Paris</city> "city" : "Paris" -- <street>Champs de Mars</street> "street" : "Champs de Mars" -- <country>France</country> "country" : "France" -- <zip>75</zip> "zip" : 75 Address_Mapping.Bind (Get_Address_Member'Access); -- Address_Mapping.Add_Mapping ("info", Property_Mapping'Access, Proxy_Info'Access); Address_Mapping.Add_Default_Mapping; -- XML: -- ---- -- <xxx id='23'> -- <address> -- <city>...</city> -- <street number='44'>..</street> -- <country>..</country> -- <zip>..</zip> -- </address> -- <name>John</name> -- <last_name>Harry</last_name> -- <age>23</age> -- <info><facebook><id>...</id></facebook></info> -- </xxx> -- Person_Mapper.Add_Mapping ("@id"); Person_Mapping.Bind (Get_Person_Member'Access); Person_Mapping.Add_Mapping ("address", Address_Mapping'Access, Proxy_Address'Access); Person_Mapping.Add_Default_Mapping; -- Person_Mapper.Add_Mapping ("info/*"); -- Person_Mapper.Add_Mapping ("address/street/@number"); Person_Vector_Mapping.Set_Mapping (Person_Mapping'Access); end Mapping;
Use the new REST support to implement the generic rest Get operation
Use the new REST support to implement the generic rest Get operation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2681fa0e2f33e7e2c38e7f3f0dd9408326708480
src/ravenports.adb
src/ravenports.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Parameters; with HelperText; with Unix; with File_Operations; with Ada.Directories; with Ada.Text_IO; package body Ravenports is package PM renames Parameters; package HT renames HelperText; package FOP renames File_Operations; package TIO renames Ada.Text_IO; package DIR renames Ada.Directories; -------------------------------------------------------------------------------------------- -- check_version_available -------------------------------------------------------------------------------------------- procedure check_version_available is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); version_loc : constant String := consdir & conspiracy_version; begin if DIR.Exists (version_loc) then if fetch_latest_version_info (temporary_ver_loc) then declare currentver : constant String := FOP.head_n1 (version_loc); latestver : constant String := FOP.head_n1 (temporary_ver_loc); begin if latestver = currentver then TIO.Put_Line ("The latest version of Ravenports, " & latestver & ", is currently installed."); else TIO.Put_Line ("A newer version of Ravenports is available: " & latestver); TIO.Put_Line ("The " & currentver & " version is currently installed."); end if; end; DIR.Delete_File (temporary_ver_loc); end if; else TIO.Put_Line ("It appears that Ravenports has not been installed at " & consdir); end if; exception when others => null; end check_version_available; -------------------------------------------------------------------------------------------- -- fetch_latest_version_info -------------------------------------------------------------------------------------------- function fetch_latest_version_info (tmp_location : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); fetch_program : constant String := sysroot & "/usr/bin/fetch"; cmd_output : HT.Text; cmd : constant String := fetch_program & " -q --no-verify-peer " & remote_version & " -o " & tmp_location; use type DIR.File_Kind; begin if not DIR.Exists ("/tmp") or else DIR.Kind ("/tmp") /= DIR.Directory then TIO.Put_Line ("The /tmp directory does not exist, bailing ..."); return False; end if; if not DIR.Exists (fetch_program) then TIO.Put_Line ("It appears that the system root has not yet been installed at " & sysroot); TIO.Put_Line ("This must be rectified before Ravenports can be checked or fetched."); return False; end if; return Unix.piped_mute_command (cmd, cmd_output); end fetch_latest_version_info; -------------------------------------------------------------------------------------------- -- fetch_latest_tarball -------------------------------------------------------------------------------------------- function fetch_latest_tarball (latest_version : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); fetch_program : constant String := sysroot & "/usr/bin/fetch"; tarball : constant String := github_archive & "/" & latest_version & ".tar.gz"; cmd_output : HT.Text; cmd : constant String := fetch_program & " -q " & tarball & " -o /tmp"; begin -- covered by previous existence checks of fetch_latest_version_info return Unix.piped_mute_command (cmd, cmd_output); end fetch_latest_tarball; -------------------------------------------------------------------------------------------- -- later_version_available -------------------------------------------------------------------------------------------- function later_version_available (available : out Boolean) return String is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); version_loc : constant String := consdir & conspiracy_version; begin available := True; -- We know consdir exists because we couldn't get here if it didn't. if fetch_latest_version_info (temporary_ver_loc) then declare latestver : constant String := FOP.head_n1 (temporary_ver_loc); begin DIR.Delete_File (temporary_ver_loc); if DIR.Exists (version_loc) then declare currentver : constant String := FOP.head_n1 (version_loc); begin if latestver = currentver then available := False; end if; end; end if; return latestver; end; else available := False; TIO.Put_Line ("Failed to fetch latest version information from Github"); return ""; end if; end later_version_available; -------------------------------------------------------------------------------------------- -- retrieve_latest_ravenports -------------------------------------------------------------------------------------------- procedure retrieve_latest_ravenports is available : Boolean; latest_version : constant String := later_version_available (available); begin if not available then TIO.Put_Line ("Ravenports update skipped as no new version is available."); return; end if; clean_up (latest_version); if not fetch_latest_tarball (latest_version) then TIO.Put_Line ("Ravenports update skipped as tarball download failed."); return; end if; if relocate_existing_ravenports and then explode_tarball_into_conspiracy (latest_version) then clean_up (latest_version); end if; end retrieve_latest_ravenports; -------------------------------------------------------------------------------------------- -- retrieve_latest_ravenports -------------------------------------------------------------------------------------------- function relocate_existing_ravenports return Boolean is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); consdir_old : constant String := consdir & ".old"; begin DIR.Rename (Old_Name => consdir, New_Name => consdir_old); return True; exception when others => return False; end relocate_existing_ravenports; -------------------------------------------------------------------------------------------- -- explode_tarball_into_conspiracy -------------------------------------------------------------------------------------------- function explode_tarball_into_conspiracy (latest_version : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); tar_program : constant String := sysroot & "/usr/bin/tar"; tarball : constant String := "/tmp/" & latest_version & ".tar.gz"; extract_dir : constant String := "/tmp/Ravenports-" & latest_version; cmd_output : HT.Text; command : constant String := tar_program & " -C /tmp -xf " & tarball; command2 : constant String := sysroot & "/bin/mv " & extract_dir & " " & consdir; begin if Unix.piped_mute_command (command, cmd_output) then return Unix.piped_mute_command (command2, cmd_output); else return False; end if; end explode_tarball_into_conspiracy; -------------------------------------------------------------------------------------------- -- clean_up -------------------------------------------------------------------------------------------- procedure clean_up (latest_version : String) is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); consdir_old : constant String := consdir & ".old"; extract_old : constant String := "/tmp/Ravenports-" & latest_version; command : constant String := sysroot & "/bin/rm -rf " & consdir_old; command2 : constant String := sysroot & "/bin/rm -rf " & extract_old; tarball : constant String := "/tmp/" & latest_version & ".tar.gz"; cmd_output : HT.Text; success : Boolean; begin if DIR.Exists (consdir_old) then success := Unix.piped_mute_command (command, cmd_output); end if; if DIR.Exists (tarball) then DIR.Delete_File (tarball); end if; if DIR.Exists (extract_old) then success := Unix.piped_mute_command (command2, cmd_output); end if; exception when others => null; end clean_up; end Ravenports;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Parameters; with HelperText; with Unix; with File_Operations; with Ada.Directories; with Ada.Text_IO; package body Ravenports is package PM renames Parameters; package HT renames HelperText; package FOP renames File_Operations; package TIO renames Ada.Text_IO; package DIR renames Ada.Directories; -------------------------------------------------------------------------------------------- -- check_version_available -------------------------------------------------------------------------------------------- procedure check_version_available is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); version_loc : constant String := consdir & conspiracy_version; begin if DIR.Exists (version_loc) then if fetch_latest_version_info (temporary_ver_loc) then declare currentver : constant String := FOP.head_n1 (version_loc); latestver : constant String := FOP.head_n1 (temporary_ver_loc); begin if latestver = currentver then TIO.Put_Line ("The latest version of Ravenports, " & latestver & ", is currently installed."); else TIO.Put_Line ("A newer version of Ravenports is available: " & latestver); TIO.Put_Line ("The " & currentver & " version is currently installed."); end if; end; DIR.Delete_File (temporary_ver_loc); end if; else TIO.Put_Line ("It appears that Ravenports has not been installed at " & consdir); end if; exception when others => null; end check_version_available; -------------------------------------------------------------------------------------------- -- fetch_latest_version_info -------------------------------------------------------------------------------------------- function fetch_latest_version_info (tmp_location : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); fetch_program : constant String := sysroot & "/usr/bin/fetch"; cmd_output : HT.Text; cmd : constant String := fetch_program & " -q --no-verify-peer " & remote_version & " -o " & tmp_location; use type DIR.File_Kind; begin if not DIR.Exists ("/tmp") or else DIR.Kind ("/tmp") /= DIR.Directory then TIO.Put_Line ("The /tmp directory does not exist, bailing ..."); return False; end if; if not DIR.Exists (fetch_program) then TIO.Put_Line ("It appears that the system root has not yet been installed at " & sysroot); TIO.Put_Line ("This must be rectified before Ravenports can be checked or fetched."); return False; end if; return Unix.piped_mute_command (cmd, cmd_output); end fetch_latest_version_info; -------------------------------------------------------------------------------------------- -- fetch_latest_tarball -------------------------------------------------------------------------------------------- function fetch_latest_tarball (latest_version : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); fetch_program : constant String := sysroot & "/usr/bin/fetch"; tarball : constant String := github_archive & "/" & latest_version & ".tar.gz"; cmd_output : HT.Text; cmd : constant String := fetch_program & " -q " & tarball & " -o /tmp"; begin -- covered by previous existence checks of fetch_latest_version_info return Unix.piped_mute_command (cmd, cmd_output); end fetch_latest_tarball; -------------------------------------------------------------------------------------------- -- later_version_available -------------------------------------------------------------------------------------------- function later_version_available (available : out Boolean) return String is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); version_loc : constant String := consdir & conspiracy_version; begin available := True; -- We know consdir exists because we couldn't get here if it didn't. if fetch_latest_version_info (temporary_ver_loc) then declare latestver : constant String := FOP.head_n1 (temporary_ver_loc); begin DIR.Delete_File (temporary_ver_loc); if DIR.Exists (version_loc) then declare currentver : constant String := FOP.head_n1 (version_loc); begin if latestver = currentver then available := False; end if; end; end if; return latestver; end; else available := False; TIO.Put_Line ("Failed to fetch latest version information from Github"); return ""; end if; end later_version_available; -------------------------------------------------------------------------------------------- -- retrieve_latest_ravenports -------------------------------------------------------------------------------------------- procedure retrieve_latest_ravenports is available : Boolean; latest_version : constant String := later_version_available (available); begin if not available then TIO.Put_Line ("Ravenports update skipped as no new version is available."); return; end if; clean_up (latest_version); if not fetch_latest_tarball (latest_version) then TIO.Put_Line ("Ravenports update skipped as tarball download failed."); return; end if; if relocate_existing_ravenports and then explode_tarball_into_conspiracy (latest_version) then clean_up (latest_version); end if; end retrieve_latest_ravenports; -------------------------------------------------------------------------------------------- -- retrieve_latest_ravenports -------------------------------------------------------------------------------------------- function relocate_existing_ravenports return Boolean is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); consdir_old : constant String := consdir & ".old"; begin DIR.Rename (Old_Name => consdir, New_Name => consdir_old); return True; exception when others => return False; end relocate_existing_ravenports; -------------------------------------------------------------------------------------------- -- explode_tarball_into_conspiracy -------------------------------------------------------------------------------------------- function explode_tarball_into_conspiracy (latest_version : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); mv_program : constant String := sysroot & "/bin/mv "; tar_program : constant String := sysroot & "/usr/bin/tar "; find_program : constant String := sysroot & "/usr/bin/find "; chmod_program : constant String := sysroot & "/bin/chmod "; tarball : constant String := "/tmp/" & latest_version & ".tar.gz"; extract_dir : constant String := "/tmp/Ravenports-" & latest_version; cmd_output : HT.Text; command : constant String := tar_program & "-C /tmp -xf " & tarball; command2 : constant String := mv_program & extract_dir & " " & consdir; command3 : constant String := find_program & consdir & " -type d -exec " & chmod_program & "555 {} +"; begin if Unix.piped_mute_command (command, cmd_output) and then Unix.piped_mute_command (command2, cmd_output) then return Unix.piped_mute_command (command3, cmd_output); else return False; end if; end explode_tarball_into_conspiracy; -------------------------------------------------------------------------------------------- -- clean_up -------------------------------------------------------------------------------------------- procedure clean_up (latest_version : String) is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); consdir_old : constant String := consdir & ".old"; extract_old : constant String := "/tmp/Ravenports-" & latest_version; command : constant String := sysroot & "/bin/rm -rf " & consdir_old; command2 : constant String := sysroot & "/bin/rm -rf " & extract_old; tarball : constant String := "/tmp/" & latest_version & ".tar.gz"; cmd_output : HT.Text; success : Boolean; begin if DIR.Exists (consdir_old) then success := Unix.piped_mute_command (command, cmd_output); end if; if DIR.Exists (tarball) then DIR.Delete_File (tarball); end if; if DIR.Exists (extract_old) then success := Unix.piped_mute_command (command2, cmd_output); end if; exception when others => null; end clean_up; end Ravenports;
modify "update-ports" command
modify "update-ports" command Set all directories of the conspiracy folder to "555" to effectively set it as a read-only folder.
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
99b04d5bc89d1e59401239497cb3c47d341280a2
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; if Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; if Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; end Memory_Allocator; end MAT.Memory.Targets;
Implement the Frame_Information procedure and protected operation
Implement the Frame_Information procedure and protected operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
62f275e0b91d8a5bff1fab66f5a34cdac024b9cd
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 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); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type; end Memory_Allocator; 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 private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; 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); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type; end Memory_Allocator; type Target_Memory is limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Change Target_Memory to a private type
Change Target_Memory to a private type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8c469afd996eb686a99d202ef587d4190bbbd3f6
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Contexts; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Contexts; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
Rename the package URLs
Rename the package URLs
Ada
apache-2.0
stcarrez/ada-security
a3c90f0c4eab99d6c16682ac5b3bde9da9f14701
src/http/aws/util-http-clients-web.adb
src/http/aws/util-http-clients-web.adb
----------------------------------------------------------------------- -- asf-clients-web -- HTTP Clients with AWS implementation -- 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 AWS.Headers.Set; with AWS.Client; with AWS.Messages; package body Util.Http.Clients.Web is Manager : aliased AWS_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; function To_Status (Code : in AWS.Messages.Status_Code) return Natural; function To_Status (Code : in AWS.Messages.Status_Code) return Natural is use AWS.Messages; begin case Code is when S100 => return 100; when S101 => return 101; when S102 => return 102; when S200 => return 200; when S201 => return 201; when S203 => return 203; when S204 => return 204; when S205 => return 205; when S206 => return 206; when S207 => return 207; when S300 => return 300; when S301 => return 301; when S302 => return 302; when S303 => return 303; when S304 => return 304; when S305 => return 305; when S307 => return 307; when S400 => return 400; when S401 => return 401; when S402 => return 402; when S403 => return 403; when S404 => return 404; when S405 => return 405; when S406 => return 406; when S407 => return 407; when S408 => return 408; when S409 => return 409; when S410 => return 410; when S411 => return 411; when S412 => return 412; when S413 => return 413; when S414 => return 414; when S415 => return 415; when S416 => return 416; when S417 => return 417; when S422 => return 422; when S423 => return 423; when S424 => return 424; when S500 => return 500; when S501 => return 501; when S502 => return 502; when S503 => return 503; when S504 => return 504; when S505 => return 505; when S507 => return 507; when others => return 500; end case; end To_Status; procedure Create (Manager : in AWS_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new AWS_Http_Request; end Create; procedure Do_Get (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers); end Do_Get; procedure Do_Post (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers); end Do_Post; -- ------------------------------ -- Returns a boolean indicating whether the named request header has already -- been set. -- ------------------------------ function Contains_Header (Http : in AWS_Http_Request; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in AWS_Http_Request; Name : in String) return String is begin return ""; end Get_Header; -- ------------------------------ -- Sets a request header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Add_Header; -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in AWS_Http_Request; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Reply : in AWS_Http_Response; Name : in String) return Boolean is begin return AWS.Response.Header (Reply.Data, Name) /= ""; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Reply : in AWS_Http_Response; Name : in String) return String is begin return AWS.Response.Header (Reply.Data, Name); end Get_Header; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Set_Header; -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Add_Header; -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in AWS_Http_Response; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ function Get_Body (Reply : in AWS_Http_Response) return String is begin return AWS.Response.Message_Body (Reply.Data); end Get_Body; -- Get the response status code. overriding function Get_Status (Reply : in AWS_Http_Response) return Natural is begin return To_Status (AWS.Response.Status_Code (Reply.Data)); end Get_Status; end Util.Http.Clients.Web;
----------------------------------------------------------------------- -- util-http-clients-web -- HTTP Clients with AWS implementation -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWS.Headers.Set; with AWS.Client; with AWS.Messages; package body Util.Http.Clients.Web is Manager : aliased AWS_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; function To_Status (Code : in AWS.Messages.Status_Code) return Natural; function To_Status (Code : in AWS.Messages.Status_Code) return Natural is use AWS.Messages; begin case Code is when S100 => return 100; when S101 => return 101; when S102 => return 102; when S200 => return 200; when S201 => return 201; when S203 => return 203; when S204 => return 204; when S205 => return 205; when S206 => return 206; when S207 => return 207; when S300 => return 300; when S301 => return 301; when S302 => return 302; when S303 => return 303; when S304 => return 304; when S305 => return 305; when S307 => return 307; when S400 => return 400; when S401 => return 401; when S402 => return 402; when S403 => return 403; when S404 => return 404; when S405 => return 405; when S406 => return 406; when S407 => return 407; when S408 => return 408; when S409 => return 409; when S410 => return 410; when S411 => return 411; when S412 => return 412; when S413 => return 413; when S414 => return 414; when S415 => return 415; when S416 => return 416; when S417 => return 417; when S422 => return 422; when S423 => return 423; when S424 => return 424; when S500 => return 500; when S501 => return 501; when S502 => return 502; when S503 => return 503; when S504 => return 504; when S505 => return 505; when S507 => return 507; when others => return 500; end case; end To_Status; procedure Create (Manager : in AWS_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new AWS_Http_Request; end Create; procedure Do_Get (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers); end Do_Get; procedure Do_Post (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers); end Do_Post; -- ------------------------------ -- Returns a boolean indicating whether the named request header has already -- been set. -- ------------------------------ function Contains_Header (Http : in AWS_Http_Request; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in AWS_Http_Request; Name : in String) return String is begin return ""; end Get_Header; -- ------------------------------ -- Sets a request header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Add_Header; -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in AWS_Http_Request; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Reply : in AWS_Http_Response; Name : in String) return Boolean is begin return AWS.Response.Header (Reply.Data, Name) /= ""; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Reply : in AWS_Http_Response; Name : in String) return String is begin return AWS.Response.Header (Reply.Data, Name); end Get_Header; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Set_Header; -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Add_Header; -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in AWS_Http_Response; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ function Get_Body (Reply : in AWS_Http_Response) return String is begin return AWS.Response.Message_Body (Reply.Data); end Get_Body; -- Get the response status code. overriding function Get_Status (Reply : in AWS_Http_Response) return Natural is begin return To_Status (AWS.Response.Status_Code (Reply.Data)); end Get_Status; end Util.Http.Clients.Web;
Fix comment header
Fix comment header
Ada
apache-2.0
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
a5da7223fa786d7aa5131ab453f5d9daed8d6360
regtests/asf-routes-tests.adb
regtests/asf-routes-tests.adb
----------------------------------------------------------------------- -- asf-routes-tests - Unit tests for ASF.Routes -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Measures; with Util.Log.Loggers; with Util.Test_Caller; with EL.Contexts.Default; package body ASF.Routes.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests"); package Caller is new Util.Test_Caller (Test, "Routes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)", Test_Add_Route_With_Path'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)", Test_Add_Route_With_Param'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)", Test_Add_Route_With_Ext'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)", Test_Add_Route_With_EL'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Iterate", Test_Iterate'Access); end Add_Tests; overriding function Get_Value (Bean : in Test_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "id" then return Util.Beans.Objects.To_Object (Bean.Id); elsif Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; overriding procedure Set_Value (Bean : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" then Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "name" then Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is begin T.Bean := new Test_Bean; ASF.Tests.EL_Test (T).Set_Up; T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"), Util.Beans.Objects.To_Object (T.Bean.all'Access)); for I in T.Routes'Range loop T.Routes (I) := new Test_Route_Type '(Index => I); end loop; end Set_Up; -- ------------------------------ -- Verify that the path matches the given route. -- ------------------------------ procedure Verify_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).all'Access; R : Route_Context_Type; begin Router.Find_Route (Path, R); declare P : constant String := Get_Path (R); begin T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path); T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path); T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path); -- Inject the path parameters in the bean instance. Inject_Parameters (R, Bean, T.ELContext.all); end; end Verify_Route; -- ------------------------------ -- Add the route associted with the path pattern. -- ------------------------------ procedure Add_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).all'Access; begin Router.Add_Route (Path, Route, T.ELContext.all); Verify_Route (T, Router, Path, Index, Bean); end Add_Route; -- ------------------------------ -- Test the Add_Route with simple fixed path components. -- Example: /list/index.html -- ------------------------------ procedure Test_Add_Route_With_Path (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/page.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); Verify_Route (T, Router, "/list/index.html", 3, Bean); end Test_Add_Route_With_Path; -- ------------------------------ -- Test the Add_Route with extension mapping. -- Example: /list/*.html -- ------------------------------ procedure Test_Add_Route_With_Ext (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/*.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean); Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean); Add_Route (T, Router, "/view/page/content/*.html", 6, Bean); Add_Route (T, Router, "/ajax/*", 7, Bean); Add_Route (T, Router, "*.html", 8, Bean); -- Verify precedence and wildcard matching. Verify_Route (T, Router, "/list/index.html", 3, Bean); Verify_Route (T, Router, "/list/admin.html", 2, Bean); Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean); Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean); Verify_Route (T, Router, "/ajax/form/save", 7, Bean); Verify_Route (T, Router, "/view/index.html", 8, Bean); end Test_Add_Route_With_Ext; -- ------------------------------ -- Test the Add_Route with fixed path components and path parameters. -- Example: /users/:id/view.html -- ------------------------------ procedure Test_Add_Route_With_Param (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/users/:id/view.html", 1, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/list.html", 2, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/index.html", 3, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path"); Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name"); Add_Route (T, Router, "/users/list/index.html", 8, Bean); Verify_Route (T, Router, "/users/1234/view.html", 1, Bean); T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id"); Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean); T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_Param; -- ------------------------------ -- Test the Add_Route with fixed path components and EL path injection. -- Example: /users/#{user.id}/view.html -- ------------------------------ procedure Test_Add_Route_With_EL (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : aliased Test_Bean; begin Add_Route (T, Router, "/users/#{user.id}", 1, Bean); Add_Route (T, Router, "/users/view.html", 2, Bean); Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean); Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean); -- Verify that the path parameters are injected in the 'user' bean (= T.Bean). Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean); T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_EL; P_1 : aliased constant String := "/list/index.html"; P_2 : aliased constant String := "/users/:id"; P_3 : aliased constant String := "/users/:id/view"; P_4 : aliased constant String := "/users/index.html"; P_5 : aliased constant String := "/users/:id/:name"; P_6 : aliased constant String := "/users/:id/:name/view.html"; P_7 : aliased constant String := "/users/:id/list"; P_8 : aliased constant String := "/users/test.html"; P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html"; P_10 : aliased constant String := "/admin/*.html"; P_11 : aliased constant String := "/admin/*.png"; P_12 : aliased constant String := "/admin/*.jpg"; P_13 : aliased constant String := "/users/:id/page/*.xml"; P_14 : aliased constant String := "/*.jsf"; type Const_String_Access is access constant String; type String_Array is array (Positive range <>) of Const_String_Access; Path_Array : constant String_Array := (P_1'Access, P_2'Access, P_3'Access, P_4'Access, P_5'Access, P_6'Access, P_7'Access, P_8'Access, P_9'Access, P_10'Access, P_11'Access, P_12'Access, P_13'Access, P_14'Access); -- ------------------------------ -- Test the Iterate over several paths. -- ------------------------------ procedure Test_Iterate (T : in out Test) is Router : Router_Type; Bean : Test_Bean; procedure Process (Pattern : in String; Route : in Route_Type_Access) is begin T.Assert (Route /= null, "The route is null for " & Pattern); T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern); Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index)); T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all, "Invalid route for " & Pattern); end Process; begin for I in Path_Array'Range loop Add_Route (T, Router, Path_Array (I).all, I, Bean); end loop; Router.Iterate (Process'Access); declare R : Route_Context_Type; St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.html", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (fixed path)"); end; declare R : Route_Context_Type; St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.jsf", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (extension)"); end; end Test_Iterate; end ASF.Routes.Tests;
----------------------------------------------------------------------- -- asf-routes-tests - Unit tests for ASF.Routes -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Measures; with Util.Log.Loggers; with Util.Test_Caller; with EL.Contexts.Default; package body ASF.Routes.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests"); package Caller is new Util.Test_Caller (Test, "Routes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)", Test_Add_Route_With_Path'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)", Test_Add_Route_With_Param'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)", Test_Add_Route_With_Ext'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)", Test_Add_Route_With_EL'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Iterate", Test_Iterate'Access); end Add_Tests; overriding function Get_Value (Bean : in Test_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "id" then return Util.Beans.Objects.To_Object (Bean.Id); elsif Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; overriding procedure Set_Value (Bean : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" then Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "name" then Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is begin T.Bean := new Test_Bean; ASF.Tests.EL_Test (T).Set_Up; T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"), Util.Beans.Objects.To_Object (T.Bean.all'Access)); for I in T.Routes'Range loop T.Routes (I) := Route_Type_Refs.Create (new Test_Route_Type '(Util.Refs.Ref_Entity with Index => I)); end loop; end Set_Up; -- ------------------------------ -- Verify that the path matches the given route. -- ------------------------------ procedure Verify_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).Value; R : Route_Context_Type; begin Router.Find_Route (Path, R); declare P : constant String := Get_Path (R); begin T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path); T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path); T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path); -- Inject the path parameters in the bean instance. Inject_Parameters (R, Bean, T.ELContext.all); end; end Verify_Route; -- ------------------------------ -- Add the route associted with the path pattern. -- ------------------------------ procedure Add_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).Value; begin Router.Add_Route (Path, Route, T.ELContext.all); Verify_Route (T, Router, Path, Index, Bean); end Add_Route; -- ------------------------------ -- Test the Add_Route with simple fixed path components. -- Example: /list/index.html -- ------------------------------ procedure Test_Add_Route_With_Path (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/page.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); Verify_Route (T, Router, "/list/index.html", 3, Bean); end Test_Add_Route_With_Path; -- ------------------------------ -- Test the Add_Route with extension mapping. -- Example: /list/*.html -- ------------------------------ procedure Test_Add_Route_With_Ext (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/*.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean); Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean); Add_Route (T, Router, "/view/page/content/*.html", 6, Bean); Add_Route (T, Router, "/ajax/*", 7, Bean); Add_Route (T, Router, "*.html", 8, Bean); -- Verify precedence and wildcard matching. Verify_Route (T, Router, "/list/index.html", 3, Bean); Verify_Route (T, Router, "/list/admin.html", 2, Bean); Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean); Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean); Verify_Route (T, Router, "/ajax/form/save", 7, Bean); Verify_Route (T, Router, "/view/index.html", 8, Bean); end Test_Add_Route_With_Ext; -- ------------------------------ -- Test the Add_Route with fixed path components and path parameters. -- Example: /users/:id/view.html -- ------------------------------ procedure Test_Add_Route_With_Param (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/users/:id/view.html", 1, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/list.html", 2, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/index.html", 3, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path"); Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name"); Add_Route (T, Router, "/users/list/index.html", 8, Bean); Verify_Route (T, Router, "/users/1234/view.html", 1, Bean); T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id"); Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean); T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_Param; -- ------------------------------ -- Test the Add_Route with fixed path components and EL path injection. -- Example: /users/#{user.id}/view.html -- ------------------------------ procedure Test_Add_Route_With_EL (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : aliased Test_Bean; begin Add_Route (T, Router, "/users/#{user.id}", 1, Bean); Add_Route (T, Router, "/users/view.html", 2, Bean); Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean); Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean); -- Verify that the path parameters are injected in the 'user' bean (= T.Bean). Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean); T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_EL; P_1 : aliased constant String := "/list/index.html"; P_2 : aliased constant String := "/users/:id"; P_3 : aliased constant String := "/users/:id/view"; P_4 : aliased constant String := "/users/index.html"; P_5 : aliased constant String := "/users/:id/:name"; P_6 : aliased constant String := "/users/:id/:name/view.html"; P_7 : aliased constant String := "/users/:id/list"; P_8 : aliased constant String := "/users/test.html"; P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html"; P_10 : aliased constant String := "/admin/*.html"; P_11 : aliased constant String := "/admin/*.png"; P_12 : aliased constant String := "/admin/*.jpg"; P_13 : aliased constant String := "/users/:id/page/*.xml"; P_14 : aliased constant String := "/*.jsf"; type Const_String_Access is access constant String; type String_Array is array (Positive range <>) of Const_String_Access; Path_Array : constant String_Array := (P_1'Access, P_2'Access, P_3'Access, P_4'Access, P_5'Access, P_6'Access, P_7'Access, P_8'Access, P_9'Access, P_10'Access, P_11'Access, P_12'Access, P_13'Access, P_14'Access); -- ------------------------------ -- Test the Iterate over several paths. -- ------------------------------ procedure Test_Iterate (T : in out Test) is Router : Router_Type; Bean : Test_Bean; procedure Process (Pattern : in String; Route : in Route_Type_Access) is begin T.Assert (Route /= null, "The route is null for " & Pattern); T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern); Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index)); T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all, "Invalid route for " & Pattern); end Process; begin for I in Path_Array'Range loop Add_Route (T, Router, Path_Array (I).all, I, Bean); end loop; Router.Iterate (Process'Access); declare R : Route_Context_Type; St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.html", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (fixed path)"); end; declare R : Route_Context_Type; St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.jsf", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (extension)"); end; end Test_Iterate; end ASF.Routes.Tests;
Update the unit tests
Update the unit tests
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
90ecfe99a8526be5d53a62eb9e258a18f286a124
src/util-streams-pipes.ads
src/util-streams-pipes.ads
----------------------------------------------------------------------- -- util-streams-pipes -- Pipe stream to or from a process -- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Processes; -- === Pipes === -- The <b>Util.Streams.Pipes</b> package defines a pipe stream to or from a process. -- The process is created and launched by the <b>Open</b> operation. The pipe allows -- to read or write to the process through the <b>Read</b> and <b>Write</b> operation. package Util.Streams.Pipes is use Util.Processes; subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE; -- ----------------------- -- Pipe stream -- ----------------------- -- The <b>Pipe_Stream</b> is an output/input stream that reads or writes -- to or from a process. type Pipe_Stream is limited new Output_Stream and Input_Stream with private; -- 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 (Stream : in out Pipe_Stream; Shell : in String); -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Input_Stream (Stream : in out Pipe_Stream; File : in String); -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Output_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Error_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- 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 (Stream : in out Pipe_Stream; Path : in String); -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ); -- Close the pipe and wait for the external process to terminate. overriding procedure Close (Stream : in out Pipe_Stream); -- Get the process exit status. function Get_Exit_Status (Stream : in Pipe_Stream) return Integer; -- Returns True if the process is running. function Is_Running (Stream : in Pipe_Stream) return Boolean; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Streams; type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record Proc : Util.Processes.Process; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Pipe_Stream); end Util.Streams.Pipes;
----------------------------------------------------------------------- -- util-streams-pipes -- Pipe stream to or from a process -- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Processes; -- === Pipes === -- The `Util.Streams.Pipes` package defines a pipe stream to or from a process. -- It allows to launch an external program while getting the program standard output or -- providing the program standard input. The `Pipe_Stream` type represents the input or -- output stream for the external program. This is a portable interface that works on -- Unix and Windows. -- -- The process is created and launched by the `Open` operation. The pipe allows -- to read or write to the process through the `Read` and `Write` operation. -- It is very close to the *popen* operation provided by the C stdio library. -- First, create the pipe instance: -- -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- -- The pipe instance can be associated with only one process at a time. -- The process is launched by using the `Open` command and by specifying the command -- to execute as well as the pipe redirection mode: -- -- * `READ` to read the process standard output, -- * `WRITE` to write the process standard input. -- -- For example to run the `ls -l` command and read its output, we could run it by using: -- -- Pipe.Open (Command => "ls -l", Mode => Util.Processes.READ); -- -- The `Pipe_Stream` is not buffered and a buffer can be configured easily by using the -- `Input_Buffer_Stream` type and doing: -- -- with Util.Streams.Buffered; -- ... -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024); -- -- And to read the process output, one can use the following: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- ... -- Buffer.Read (Into => Content); -- -- The pipe object should be closed when reading or writing to it is finished. -- By closing the pipe, the caller will wait for the termination of the process. -- The process exit status can be obtained by using the `Get_Exit_Status` function. -- -- Pipe.Close; -- if Pipe.Get_Exit_Status /= 0 then -- Ada.Text_IO.Put_Line ("Command exited with status " -- & Integer'Image (Pipe.Get_Exit_Status)); -- end if; -- -- You will note that the `Pipe_Stream` is a limited type and thus cannot be copied. -- When leaving the scope of the `Pipe_Stream` instance, the application will wait for -- the process to terminate. package Util.Streams.Pipes is use Util.Processes; subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE; -- ----------------------- -- Pipe stream -- ----------------------- -- The <b>Pipe_Stream</b> is an output/input stream that reads or writes -- to or from a process. type Pipe_Stream is limited new Output_Stream and Input_Stream with private; -- 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 (Stream : in out Pipe_Stream; Shell : in String); -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Input_Stream (Stream : in out Pipe_Stream; File : in String); -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Output_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Error_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- 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 (Stream : in out Pipe_Stream; Path : in String); -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ); -- Close the pipe and wait for the external process to terminate. overriding procedure Close (Stream : in out Pipe_Stream); -- Get the process exit status. function Get_Exit_Status (Stream : in Pipe_Stream) return Integer; -- Returns True if the process is running. function Is_Running (Stream : in Pipe_Stream) return Boolean; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Streams; type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record Proc : Util.Processes.Process; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Pipe_Stream); end Util.Streams.Pipes;
Document the pipe streams
Document the pipe streams
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
faca5ebb1390480f09d7b027cb017010e397204f
src/util-streams-buffered-encoders.adb
src/util-streams-buffered-encoders.adb
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- 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.Encoders.Base64; package body Util.Streams.Buffered.Encoders is -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- procedure Initialize (Stream : in out Encoding_Stream; Output : in Output_Stream_Access; Size : in Natural; Format : in String) is begin Stream.Initialize (Output, Size); Stream.Transform := new Util.Encoders.Base64.Encoder; end Initialize; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Encoding_Stream) is begin Stream.Flush; Stream.Output.Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Encoding_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First; Last_Encoded : Ada.Streams.Stream_Element_Offset; Last_Pos : Ada.Streams.Stream_Element_Offset; begin while First_Encoded <= Buffer'Last loop Stream.Transform.Transform (Data => Buffer (First_Encoded .. Buffer'Last), Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last => Last_Pos, Encoded => Last_Encoded); if Last_Encoded < Buffer'Last then Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Write_Pos := Stream.Buffer'First; else Stream.Write_Pos := Last_Pos + 1; end if; First_Encoded := Last_Encoded + 1; end loop; end Write; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Encoding_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset; begin Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last_Pos); Stream.Write_Pos := Last_Pos + 1; Output_Buffer_Stream (Stream).Flush; end Flush; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Encoding_Stream) is begin null; end Finalize; end Util.Streams.Buffered.Encoders;
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- 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.Encoders.Base64; package body Util.Streams.Buffered.Encoders is -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- procedure Initialize (Stream : in out Encoding_Stream; Output : in Output_Stream_Access; Size : in Natural; Format : in String) is pragma Unreferenced (Format); begin Stream.Initialize (Output, Size); Stream.Transform := new Util.Encoders.Base64.Encoder; end Initialize; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Encoding_Stream) is begin Stream.Flush; Stream.Output.Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Encoding_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First; Last_Encoded : Ada.Streams.Stream_Element_Offset; Last_Pos : Ada.Streams.Stream_Element_Offset; begin while First_Encoded <= Buffer'Last loop Stream.Transform.Transform (Data => Buffer (First_Encoded .. Buffer'Last), Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last => Last_Pos, Encoded => Last_Encoded); if Last_Encoded < Buffer'Last then Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Write_Pos := Stream.Buffer'First; else Stream.Write_Pos := Last_Pos + 1; end if; First_Encoded := Last_Encoded + 1; end loop; end Write; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Encoding_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset := Stream.Write_Pos - 1; begin Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last_Pos); Stream.Write_Pos := Last_Pos + 1; Output_Buffer_Stream (Stream).Flush; end Flush; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Encoding_Stream) is begin null; end Finalize; end Util.Streams.Buffered.Encoders;
Fix compilation warning reported in the Flush procedure
Fix compilation warning reported in the Flush procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e66bc28987f7cf89595382d0b184487e8d7b9249
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; synth_version_major : constant String := "1"; synth_version_minor : constant String := "41"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "42"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
Bump to version v1.42
Bump to version v1.42
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
503536a7a8e5700d802ee7fe017b923882c00b0b
awa/plugins/awa-comments/src/awa-comments-modules.adb
awa/plugins/awa-comments/src/awa-comments-modules.adb
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Sessions; with Security.Permissions; with AWA.Users.Models; with AWA.Permissions; with AWA.Modules.Beans; with AWA.Services.Contexts; with AWA.Comments.Beans; package body AWA.Comments.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module"); package Register is new AWA.Modules.Beans (Module => Comment_Module, Module_Access => Comment_Module_Access); -- ------------------------------ -- Initialize the comments module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the comments module"); -- Register the comment list bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_List_Bean", Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access); -- Register the comment bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_Bean", Handler => AWA.Comments.Beans.Create_Comment_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Load the comment identified by the given identifier. -- ------------------------------ procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Comment.Load (DB, Id, Found); end Load_Comment; -- Create a new comment for the associated database entity. procedure Create_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment.Get_Entity_Id); Comment.Set_Author (User); Comment.Set_Create_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; end Create_Comment; end AWA.Comments.Modules;
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Sessions; with ADO.Sessions.Entities; with Security.Permissions; with AWA.Users.Models; with AWA.Permissions; with AWA.Modules.Beans; with AWA.Services.Contexts; with AWA.Comments.Beans; package body AWA.Comments.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module"); package Register is new AWA.Modules.Beans (Module => Comment_Module, Module_Access => Comment_Module_Access); -- ------------------------------ -- Initialize the comments module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the comments module"); -- Register the comment list bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_List_Bean", Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access); -- Register the comment bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_Bean", Handler => AWA.Comments.Beans.Create_Comment_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Load the comment identified by the given identifier. -- ------------------------------ procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Comment.Load (DB, Id, Found); end Load_Comment; -- ------------------------------ -- Create a new comment for the associated database entity. -- ------------------------------ procedure Create_Comment (Model : in Comment_Module; Permission : in String; Entity_Type : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment.Get_Entity_Id); Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type)); Comment.Set_Author (User); Comment.Set_Create_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; end Create_Comment; end AWA.Comments.Modules;
Use the entity type parameter to setup the new comment
Use the entity type parameter to setup the new comment
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5d0fffa5f1dbb188647d60e7a972822b1906ba5a
regtests/util-streams-texts-tests.adb
regtests/util-streams-texts-tests.adb
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2012, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; package body Util.Streams.Texts.Tests is use Ada.Streams.Stream_IO; use Util.Tests; package Caller is new Util.Test_Caller (Test, "Streams.Texts"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Texts.Open, Read_Line, Close", Test_Read_Line'Access); Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Integer)", Test_Write_Integer'Access); end Add_Tests; -- ------------------------------ -- Test reading a text stream. -- ------------------------------ procedure Test_Read_Line (T : in out Test) is Stream : aliased Files.File_Stream; Reader : Util.Streams.Texts.Reader_Stream; Count : Natural := 0; begin Stream.Open (Name => "Makefile", Mode => In_File); Reader.Initialize (From => Stream'Access); while not Reader.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Reader.Read_Line (Line); Count := Count + 1; end; end loop; Stream.Close; T.Assert (Count > 100, "Too few lines read"); end Test_Read_Line; -- ------------------------------ -- Write on a text stream converting an integer and writing it. -- ------------------------------ procedure Test_Write_Integer (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 4); -- Write '0' (we don't want the Ada spurious space). Stream.Write (Integer (0)); Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '1234' Stream.Write (Integer (1234)); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "1234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '-234' Stream.Write (Integer (-234)); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "-234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Write_Integer; end Util.Streams.Texts.Tests;
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2012, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; package body Util.Streams.Texts.Tests is use Ada.Streams.Stream_IO; use Util.Tests; package Caller is new Util.Test_Caller (Test, "Streams.Texts"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Texts.Open, Read_Line, Close", Test_Read_Line'Access); Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Integer)", Test_Write_Integer'Access); Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Long_Long_Integer)", Test_Write_Long_Integer'Access); end Add_Tests; -- ------------------------------ -- Test reading a text stream. -- ------------------------------ procedure Test_Read_Line (T : in out Test) is Stream : aliased Files.File_Stream; Reader : Util.Streams.Texts.Reader_Stream; Count : Natural := 0; begin Stream.Open (Name => "Makefile", Mode => In_File); Reader.Initialize (From => Stream'Access); while not Reader.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Reader.Read_Line (Line); Count := Count + 1; end; end loop; Stream.Close; T.Assert (Count > 100, "Too few lines read"); end Test_Read_Line; -- ------------------------------ -- Write on a text stream converting an integer and writing it. -- ------------------------------ procedure Test_Write_Integer (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 4); -- Write '0' (we don't want the Ada spurious space). Stream.Write (Integer (0)); Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '1234' Stream.Write (Integer (1234)); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "1234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '-234' Stream.Write (Integer (-234)); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "-234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Write_Integer; -- ------------------------------ -- Write on a text stream converting an integer and writing it. -- ------------------------------ procedure Test_Write_Long_Integer (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 64); -- Write '0' (we don't want the Ada spurious space). Stream.Write (Long_Long_Integer (0)); Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '1234' Stream.Write (Long_Long_Integer (123456789012345)); Assert_Equals (T, 15, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 15, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "123456789012345", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '-2345678901234' Stream.Write (Long_Long_Integer (-2345678901234)); Assert_Equals (T, 14, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 14, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "-2345678901234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Write_Long_Integer; end Util.Streams.Texts.Tests;
Implement Test_Write_Long_Integer and register the new test for execution
Implement Test_Write_Long_Integer and register the new test for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e6144622a95b069e3ec71c51a200b5a72d35cb6e
boards/stm32_common/stm32f469disco/framebuffer_otm8009a.ads
boards/stm32_common/stm32f469disco/framebuffer_otm8009a.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2017, 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 the copyright holder 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. -- -- -- ------------------------------------------------------------------------------ with HAL; use HAL; with HAL.Framebuffer; use HAL.Framebuffer; with HAL.Bitmap; with Framebuffer_DSI; private with STM32.Device; private with STM32.DMA2D_Bitmap; private with STM32.DSI; private with STM32.GPIO; package Framebuffer_OTM8009A is LCD_Natural_Width : constant := Framebuffer_DSI.LCD_Natural_Width; LCD_Natural_Height : constant := Framebuffer_DSI.LCD_Natural_Width; type Frame_Buffer is limited new HAL.Framebuffer.Frame_Buffer_Display with private; procedure Initialize (Display : in out Frame_Buffer; Orientation : HAL.Framebuffer.Display_Orientation := Default; Mode : HAL.Framebuffer.Wait_Mode := Interrupt); private DSI_RESET : STM32.GPIO.GPIO_Point renames STM32.Device.PH7; PLLSAIN : constant := 417; PLLSAIR : constant := 5; PLLSAI_DIVR : constant := 2; PLL_N_Div : constant := 125; PLL_IN_Div : constant STM32.DSI.DSI_PLL_IDF := STM32.DSI.PLL_IN_DIV2; PLL_OUT_Div : constant STM32.DSI.DSI_PLL_ODF := STM32.DSI.PLL_OUT_DIV1; type Frame_Buffer is limited new Framebuffer_DSI.Frame_Buffer with null record; end Framebuffer_OTM8009A;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2017, 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 the copyright holder 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. -- -- -- ------------------------------------------------------------------------------ with HAL; use HAL; with HAL.Framebuffer; use HAL.Framebuffer; with HAL.Bitmap; with Framebuffer_DSI; private with STM32.Device; private with STM32.DMA2D_Bitmap; private with STM32.DSI; private with STM32.GPIO; package Framebuffer_OTM8009A is LCD_Natural_Width : constant := Framebuffer_DSI.LCD_Natural_Width; LCD_Natural_Height : constant := Framebuffer_DSI.LCD_Natural_Height; type Frame_Buffer is limited new HAL.Framebuffer.Frame_Buffer_Display with private; procedure Initialize (Display : in out Frame_Buffer; Orientation : HAL.Framebuffer.Display_Orientation := Default; Mode : HAL.Framebuffer.Wait_Mode := Interrupt); private DSI_RESET : STM32.GPIO.GPIO_Point renames STM32.Device.PH7; PLLSAIN : constant := 417; PLLSAIR : constant := 5; PLLSAI_DIVR : constant := 2; PLL_N_Div : constant := 125; PLL_IN_Div : constant STM32.DSI.DSI_PLL_IDF := STM32.DSI.PLL_IN_DIV2; PLL_OUT_Div : constant STM32.DSI.DSI_PLL_ODF := STM32.DSI.PLL_OUT_DIV1; type Frame_Buffer is limited new Framebuffer_DSI.Frame_Buffer with null record; end Framebuffer_OTM8009A;
Fix Typo in screen Height
framebuffer_otm8009a: Fix Typo in screen Height
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
030a3adb79beb38932c22d28b7d78a7cf938e9ae
regtests/security-permissions-tests.ads
regtests/security-permissions-tests.ads
----------------------------------------------------------------------- -- Security-permissions-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Security.Permissions.Tests is package P_Admin is new Permissions.Definition ("admin"); package P_Create is new Permissions.Definition ("create"); package P_Update is new Permissions.Definition ("update"); package P_Delete is new Permissions.Definition ("delete"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test Add_Permission and Get_Permission_Index procedure Test_Add_Permission (T : in out Test); -- Test the permission created by the Definition package. procedure Test_Define_Permission (T : in out Test); -- Test Get_Permission on invalid permission name. procedure Test_Get_Invalid_Permission (T : in out Test); end Security.Permissions.Tests;
----------------------------------------------------------------------- -- Security-permissions-tests - Unit tests for Security.Permissions -- Copyright (C) 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 Util.Tests; package Security.Permissions.Tests is package P_Admin is new Permissions.Definition ("admin"); package P_Create is new Permissions.Definition ("create"); package P_Update is new Permissions.Definition ("update"); package P_Delete is new Permissions.Definition ("delete"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test Add_Permission and Get_Permission_Index. procedure Test_Add_Permission (T : in out Test); -- Test the permission created by the Definition package. procedure Test_Define_Permission (T : in out Test); -- Test Get_Permission on invalid permission name. procedure Test_Get_Invalid_Permission (T : in out Test); -- Test operations on the Permission_Index_Set. procedure Test_Add_Permission_Set (T : in out Test); end Security.Permissions.Tests;
Declare the Test_Add_Permission_Set unit test
Declare the Test_Add_Permission_Set unit test
Ada
apache-2.0
stcarrez/ada-security
83ce69d1eafe98bf08134ce638deafdd15ea8204
awa/plugins/awa-jobs/src/awa-jobs-services.ads
awa/plugins/awa-jobs/src/awa-jobs-services.ads
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Objects.Maps; with ASF.Applications; with ADO.Sessions; with AWA.Events; with AWA.Jobs.Models; package AWA.Jobs.Services is Closed_Error : exception; Schedule_Error : exception; Invalid_Value : exception; -- Event posted when a job is created. package Job_Create_Event is new AWA.Events.Definition (Name => "job-create"); -- ------------------------------ -- Abstract_Job Type -- ------------------------------ -- The <b>Abstract_Job_Type</b> is an abstract tagged record which defines a job that can be -- scheduled and executed. type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Abstract_Job_Access is access all Abstract_Job_Type'Class; -- ------------------------------ -- Job Factory -- ------------------------------ type Job_Factory is abstract tagged limited null record; type Job_Factory_Access is access all Job_Factory'Class; -- Create the job instance using the job factory. function Create (Factory : in Job_Factory) return Abstract_Job_Access is abstract; -- Get the job factory name. function Get_Name (Factory : in Job_Factory'Class) return String; -- Execute the job. This operation must be implemented and should perform the work -- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve -- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result. procedure Execute (Job : in out Abstract_Job_Type) is abstract; -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String); -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String; -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object; -- Get the job status. function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type; -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type); -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class); -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class); -- ------------------------------ -- Work Factory -- ------------------------------ type Work_Access is access procedure (Job : in out Abstract_Job_Type'Class); type Work_Factory (Work : Work_Access) is new Job_Factory with null record; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access; -- ------------------------------ -- -- ------------------------------ type Job_Type is new Abstract_Job_Type with private; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class); procedure Execute (Job : in out Job_Type); -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. generic type T is new Abstract_Job_Type with private; package Definition is type Job_Type_Factory is new Job_Factory with null record; overriding function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access; Factory : aliased Job_Type_Factory; end Definition; generic Work : in Work_Access; package Work_Definition is type S_Factory is new Work_Factory with null record; Factory : aliased S_Factory := S_Factory '(Work => Work); end Work_Definition; private type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with record Job : AWA.Jobs.Models.Job_Ref; Props : Util.Beans.Objects.Maps.Map; Results : Util.Beans.Objects.Maps.Map; Props_Modified : Boolean := False; Results_Modified : Boolean := False; end record; type Job_Type is new Abstract_Job_Type with record Work : Work_Access; end record; end AWA.Jobs.Services;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Maps; with ADO.Sessions; with AWA.Events; with AWA.Jobs.Models; package AWA.Jobs.Services is Closed_Error : exception; Schedule_Error : exception; Invalid_Value : exception; -- Event posted when a job is created. package Job_Create_Event is new AWA.Events.Definition (Name => "job-create"); -- ------------------------------ -- Abstract_Job Type -- ------------------------------ -- The <b>Abstract_Job_Type</b> is an abstract tagged record which defines a job that can be -- scheduled and executed. type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Abstract_Job_Access is access all Abstract_Job_Type'Class; -- ------------------------------ -- Job Factory -- ------------------------------ type Job_Factory is abstract tagged limited null record; type Job_Factory_Access is access all Job_Factory'Class; -- Create the job instance using the job factory. function Create (Factory : in Job_Factory) return Abstract_Job_Access is abstract; -- Get the job factory name. function Get_Name (Factory : in Job_Factory'Class) return String; -- Execute the job. This operation must be implemented and should perform the work -- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve -- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result. procedure Execute (Job : in out Abstract_Job_Type) is abstract; -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String); -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String; -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object; -- Get the job status. function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type; -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type); -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class); -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class); -- ------------------------------ -- Work Factory -- ------------------------------ type Work_Access is access procedure (Job : in out Abstract_Job_Type'Class); type Work_Factory (Work : Work_Access) is new Job_Factory with null record; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access; -- ------------------------------ -- -- ------------------------------ type Job_Type is new Abstract_Job_Type with private; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class); procedure Execute (Job : in out Job_Type); -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. generic type T is new Abstract_Job_Type with private; package Definition is type Job_Type_Factory is new Job_Factory with null record; overriding function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access; Factory : aliased Job_Type_Factory; end Definition; generic Work : in Work_Access; package Work_Definition is type S_Factory is new Work_Factory with null record; Factory : aliased S_Factory := S_Factory '(Work => Work); end Work_Definition; private type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with record Job : AWA.Jobs.Models.Job_Ref; Props : Util.Beans.Objects.Maps.Map; Results : Util.Beans.Objects.Maps.Map; Props_Modified : Boolean := False; Results_Modified : Boolean := False; end record; type Job_Type is new Abstract_Job_Type with record Work : Work_Access; end record; end AWA.Jobs.Services;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
889e3db532828a7ddb9ff7a454b904780cca66b3
src/base/commands/util-commands-parsers-gnat_parser.adb
src/base/commands/util-commands-parsers-gnat_parser.adb
----------------------------------------------------------------------- -- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.OS_Lib; package body Util.Commands.Parsers.GNAT_Parser is function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access; function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access is Count : constant Natural := Args.Get_Count; New_Arg : GNAT.OS_Lib.Argument_List (1 .. Count); begin for I in 1 .. Count loop New_Arg (I) := new String '(Args.Get_Argument (I)); end loop; return new GNAT.OS_Lib.Argument_List '(New_Arg); end To_OS_Lib_Argument_List; -- ------------------------------ -- Get all the remaining arguments from the GNAT command line parse. -- ------------------------------ procedure Get_Arguments (List : in out Dynamic_Argument_List; Command : in String; Parser : in GC.Opt_Parser := GC.Command_Line_Parser) is begin List.Name := Ada.Strings.Unbounded.To_Unbounded_String (Command); loop declare S : constant String := GC.Get_Argument (Parser => Parser); begin exit when S'Length = 0; List.List.Append (S); end; end loop; end Get_Arguments; procedure Execute (Config : in out Config_Type; Args : in Util.Commands.Argument_List'Class; Process : access procedure (Cmd_Args : in Commands.Argument_List'Class)) is use type GC.Command_Line_Configuration; Empty : Config_Type; begin if Config /= Empty then declare Parser : GC.Opt_Parser; Cmd_Args : Dynamic_Argument_List; Params : GNAT.OS_Lib.Argument_List_Access := To_OS_Lib_Argument_List (Args); begin GC.Initialize_Option_Scan (Parser, Params); GC.Getopt (Config => Config, Parser => Parser); Get_Arguments (Cmd_Args, Args.Get_Command_Name, Parser); Process (Cmd_Args); GC.Free (Config); GNAT.OS_Lib.Free (Params); exception when others => GNAT.OS_Lib.Free (Params); GC.Free (Config); raise; end; else Process (Args); end if; end Execute; procedure Usage (Name : in String; Config : in out Config_Type) is begin GC.Set_Usage (Config, Usage => Name & " [switches] [arguments]"); GC.Display_Help (Config); end Usage; end Util.Commands.Parsers.GNAT_Parser;
----------------------------------------------------------------------- -- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.OS_Lib; package body Util.Commands.Parsers.GNAT_Parser is function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access; function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access is Count : constant Natural := Args.Get_Count; New_Arg : GNAT.OS_Lib.Argument_List (1 .. Count); begin for I in 1 .. Count loop New_Arg (I) := new String '(Args.Get_Argument (I)); end loop; return new GNAT.OS_Lib.Argument_List '(New_Arg); end To_OS_Lib_Argument_List; -- ------------------------------ -- Get all the remaining arguments from the GNAT command line parse. -- ------------------------------ procedure Get_Arguments (List : in out Dynamic_Argument_List; Command : in String; Parser : in GC.Opt_Parser := GC.Command_Line_Parser) is begin List.Name := Ada.Strings.Unbounded.To_Unbounded_String (Command); loop declare S : constant String := GC.Get_Argument (Parser => Parser); begin exit when S'Length = 0; List.List.Append (S); end; end loop; end Get_Arguments; procedure Execute (Config : in out Config_Type; Args : in Util.Commands.Argument_List'Class; Process : access procedure (Cmd_Args : in Commands.Argument_List'Class)) is use type GC.Command_Line_Configuration; Empty : Config_Type; begin if Config /= Empty then declare Parser : GC.Opt_Parser; Cmd_Args : Dynamic_Argument_List; Params : GNAT.OS_Lib.Argument_List_Access := To_OS_Lib_Argument_List (Args); begin GC.Initialize_Option_Scan (Parser, Params); GC.Getopt (Config => Config, Parser => Parser); Get_Arguments (Cmd_Args, Args.Get_Command_Name, Parser); Process (Cmd_Args); GC.Free (Config); GNAT.OS_Lib.Free (Params); exception when others => GNAT.OS_Lib.Free (Params); GC.Free (Config); raise; end; else Process (Args); end if; end Execute; procedure Usage (Name : in String; Config : in out Config_Type) is Opts : constant String := GC.Get_Switches (Config); begin if Opts'Length > 0 then GC.Set_Usage (Config, Usage => Name & " [switches] [arguments]"); GC.Display_Help (Config); end if; end Usage; end Util.Commands.Parsers.GNAT_Parser;
Use Get_Switches to check that there are some switches on the config If there are no switch, don't call Display_Help because it will crash
Use Get_Switches to check that there are some switches on the config If there are no switch, don't call Display_Help because it will crash
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5bee483dc1fdfe28ec2df5e95116d22d67f8c5fc
src/base/log/util-log-appenders-rolling_files.ads
src/base/log/util-log-appenders-rolling_files.ads
----------------------------------------------------------------------- -- util-log-appenders-rolling_files -- Rolling file log appenders -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Util.Properties; private with Util.Refs; private with Util.Files.Rolling; -- The `RollingFile` appender recognises the following configurations: -- -- | Name | Description | -- | -------------- | -------------------------------------------------------------- | -- | layout | Defines the format of the message printed by the appender. | -- | level | Defines the minimum level above which messages are printed. | -- | fileName | The name of the file to write to. If the file, or any of its parent | -- | | directories, do not exist, they will be created. | -- | filePattern | The pattern of the file name of the archived log file. The pattern | -- | | can contain '%i' which are replaced by a counter incremented at each | -- | | rollover, a '%d' is replaced by a date pattern. | -- | append | When 'true' or '1', the file is opened in append mode otherwise | -- | | it is truncated (the default is to truncate). | -- | immediateFlush | When 'true' or '1', the file is flushed after each message log. | -- | | Immediate flush is useful in some situations to have the log file | -- | | updated immediately at the expense of slowing down the processing | -- | | of logs. | -- | policy | The triggering policy which drives when a rolling is performed. | -- | | Possible values are: `none`, `size`, `time` | -- | strategy | The strategy to use to determine the name and location of the | -- | | archive file. Possible values are: `ascending`, `descending`, and | -- | | `direct`. Default is `ascending`. | -- | policyInterval | How often a rollover should occur based on the most specific time | -- | | unit in the date pattern. For example, with a date pattern with | -- | | hours as the most specific item and and increment of 4 rollovers | -- | | would occur every 4 hours. The default value is 1. | -- | policyMin | The minimum value of the counter. The default value is 1. | -- | policyMax | The maximum value of the counter. Once this values is reached older | -- | | archives will be deleted on subsequent rollovers. The default | -- | | value is 7. | -- | minSize | The minimum size the file must have to roll over. | package Util.Log.Appenders.Rolling_Files is -- ------------------------------ -- File appender -- ------------------------------ type File_Appender (Length : Positive) is new Appender with private; type File_Appender_Access is access all File_Appender'Class; overriding procedure Append (Self : in out File_Appender; Message : in Util.Strings.Builders.Builder; Date : in Ada.Calendar.Time; Level : in Level_Type; Logger : in String); -- Flush the log events. overriding procedure Flush (Self : in out File_Appender); -- Flush and close the file. overriding procedure Finalize (Self : in out File_Appender); -- Create a file appender and configure it according to the properties function Create (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; private type File_Entity is new Util.Refs.Ref_Entity with record Output : Ada.Text_IO.File_Type; end record; type File_Access is access all File_Entity; -- Finalize the referenced object. This is called before the object is freed. overriding procedure Finalize (Object : in out File_Entity); package File_Refs is new Util.Refs.References (File_Entity, File_Access); protected type Rolling_File is procedure Initialize (Name : in String; Base : in String; Properties : in Util.Properties.Manager); procedure Openlog (File : out File_Refs.Ref); procedure Flush (File : out File_Refs.Ref); procedure Closelog; private Manager : Util.Files.Rolling.File_Manager; Current : File_Refs.Ref; Append : Boolean; end Rolling_File; type File_Appender (Length : Positive) is new Appender (Length) with record Immediate_Flush : Boolean := False; File : Rolling_File; end record; end Util.Log.Appenders.Rolling_Files;
----------------------------------------------------------------------- -- util-log-appenders-rolling_files -- Rolling file log appenders -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Util.Properties; private with Util.Refs; private with Util.Files.Rolling; -- === Rolling file appender === -- The `RollingFile` appender recognises the following configurations: -- -- | Name | Description | -- | -------------- | -------------------------------------------------------------- | -- | layout | Defines the format of the message printed by the appender. | -- | level | Defines the minimum level above which messages are printed. | -- | fileName | The name of the file to write to. If the file, or any of its parent | -- | | directories, do not exist, they will be created. | -- | filePattern | The pattern of the file name of the archived log file. The pattern | -- | | can contain '%i' which are replaced by a counter incremented at each | -- | | rollover, a '%d' is replaced by a date pattern. | -- | append | When 'true' or '1', the file is opened in append mode otherwise | -- | | it is truncated (the default is to truncate). | -- | immediateFlush | When 'true' or '1', the file is flushed after each message log. | -- | | Immediate flush is useful in some situations to have the log file | -- | | updated immediately at the expense of slowing down the processing | -- | | of logs. | -- | policy | The triggering policy which drives when a rolling is performed. | -- | | Possible values are: `none`, `size`, `time` | -- | strategy | The strategy to use to determine the name and location of the | -- | | archive file. Possible values are: `ascending`, `descending`, and | -- | | `direct`. Default is `ascending`. | -- | policyInterval | How often a rollover should occur based on the most specific time | -- | | unit in the date pattern. For example, with a date pattern with | -- | | hours as the most specific item and and increment of 4 rollovers | -- | | would occur every 4 hours. The default value is 1. | -- | policyMin | The minimum value of the counter. The default value is 1. | -- | policyMax | The maximum value of the counter. Once this values is reached older | -- | | archives will be deleted on subsequent rollovers. The default | -- | | value is 7. | -- | minSize | The minimum size the file must have to roll over. | package Util.Log.Appenders.Rolling_Files is -- ------------------------------ -- File appender -- ------------------------------ type File_Appender (Length : Positive) is new Appender with private; type File_Appender_Access is access all File_Appender'Class; overriding procedure Append (Self : in out File_Appender; Message : in Util.Strings.Builders.Builder; Date : in Ada.Calendar.Time; Level : in Level_Type; Logger : in String); -- Flush the log events. overriding procedure Flush (Self : in out File_Appender); -- Flush and close the file. overriding procedure Finalize (Self : in out File_Appender); -- Create a file appender and configure it according to the properties function Create (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; private type File_Entity is new Util.Refs.Ref_Entity with record Output : Ada.Text_IO.File_Type; end record; type File_Access is access all File_Entity; -- Finalize the referenced object. This is called before the object is freed. overriding procedure Finalize (Object : in out File_Entity); package File_Refs is new Util.Refs.References (File_Entity, File_Access); protected type Rolling_File is procedure Initialize (Name : in String; Base : in String; Properties : in Util.Properties.Manager); procedure Openlog (File : out File_Refs.Ref); procedure Flush (File : out File_Refs.Ref); procedure Closelog; private Manager : Util.Files.Rolling.File_Manager; Current : File_Refs.Ref; Append : Boolean; end Rolling_File; type File_Appender (Length : Positive) is new Appender (Length) with record Immediate_Flush : Boolean := False; File : Rolling_File; end record; end Util.Log.Appenders.Rolling_Files;
Add documentation for the configuration
Add documentation for the configuration
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4ddbe718a34c6fa108a7d9a299e0107e3010106c
src/aws/asf-responses-web.adb
src/aws/asf-responses-web.adb
----------------------------------------------------------------------- -- asf.responses.web -- ASF Responses with AWS server -- 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 AWS.Headers; with AWS.Messages; with AWS.Response.Set; with AWS.Containers.Tables; package body ASF.Responses.Web is procedure Initialize (Resp : in out Response) is begin Resp.Content.Initialize (Size => 256 * 1024, Output => Resp'Unchecked_Access, Input => null); Resp.Stream := Resp.Content'Unchecked_Access; end Initialize; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ procedure Write (Stream : in out Response; Buffer : in Ada.Streams.Stream_Element_Array) is begin AWS.Response.Set.Append_Body (D => Stream.Data, Item => Buffer); end Write; -- ------------------------------ -- Flush the buffer (if any) to the sink. -- ------------------------------ procedure Flush (Stream : in out Response) is begin null; end Flush; function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code; function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code is use AWS.Messages; begin case Status is when 100 => return S100; when 101 => return S101; when 200 => return S200; when 201 => return S201; when 202 => return S202; when 301 => return S301; when 302 => return S302; when 400 => return S400; when 401 => return S401; when 402 => return S402; when 403 => return S403; when 404 => return S404; when others => return S500; end case; end To_Status_Code; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Resp : in Response; Process : not null access procedure (Name : in String; Value : in String)) is Headers : constant AWS.Headers.List := AWS.Response.Header (Resp.Data); begin AWS.Containers.Tables.Iterate_Names (AWS.Containers.Tables.Table_Type (Headers), ";", Process); end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Resp : in Response; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- ------------------------------ -- Sets a response header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ procedure Set_Header (Resp : in out Response; Name : in String; Value : in String) is begin if AWS.Response.Header (Resp.Data, Name)'Length = 0 then AWS.Response.Set.Add_Header (D => Resp.Data, Name => Name, Value => Value); end if; end Set_Header; -- ------------------------------ -- Adds a response header with the given name and value. -- This method allows response headers to have multiple values. -- ------------------------------ procedure Add_Header (Resp : in out Response; Name : in String; Value : in String) is begin AWS.Response.Set.Add_Header (D => Resp.Data, Name => Name, Value => Value); end Add_Header; -- ------------------------------ -- Sends a temporary redirect response to the client using the specified redirect -- location URL. This method can accept relative URLs; the servlet container must -- convert the relative URL to an absolute URL before sending the response to the -- client. If the location is relative without a leading '/' the container -- interprets it as relative to the current request URI. If the location is relative -- with a leading '/' the container interprets it as relative to the servlet -- container root. -- -- If the response has already been committed, this method throws an -- IllegalStateException. After using this method, the response should be -- considered to be committed and should not be written to. -- ------------------------------ procedure Send_Redirect (Resp : in out Response; Location : in String) is begin Response'Class (Resp).Set_Status (SC_FOUND); Response'Class (Resp).Set_Header (Name => "Location", Value => Location); Resp.Redirect := True; end Send_Redirect; -- ------------------------------ -- Prepare the response data by collecting the status, content type and message body. -- ------------------------------ procedure Build (Resp : in out Response) is begin if not Resp.Redirect then AWS.Response.Set.Content_Type (D => Resp.Data, Value => Resp.Get_Content_Type); Resp.Content.Flush; if AWS.Response.Is_Empty (Resp.Data) then AWS.Response.Set.Message_Body (Resp.Data, ""); end if; else AWS.Response.Set.Mode (D => Resp.Data, Value => AWS.Response.Header); end if; AWS.Response.Set.Status_Code (D => Resp.Data, Value => To_Status_Code (Resp.Get_Status)); end Build; -- ------------------------------ -- Get the response data -- ------------------------------ function Get_Data (Resp : in Response) return AWS.Response.Data is begin return Resp.Data; end Get_Data; end ASF.Responses.Web;
----------------------------------------------------------------------- -- asf.responses.web -- ASF Responses with AWS server -- Copyright (C) 2009, 2010, 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWS.Headers; with AWS.Messages; with AWS.Response.Set; with AWS.Containers.Tables; package body ASF.Responses.Web is procedure Initialize (Resp : in out Response) is begin Resp.Content.Initialize (Size => 256 * 1024, Output => Resp'Unchecked_Access); Resp.Stream := Resp.Content'Unchecked_Access; end Initialize; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ procedure Write (Stream : in out Response; Buffer : in Ada.Streams.Stream_Element_Array) is begin AWS.Response.Set.Append_Body (D => Stream.Data, Item => Buffer); end Write; -- ------------------------------ -- Flush the buffer (if any) to the sink. -- ------------------------------ procedure Flush (Stream : in out Response) is begin null; end Flush; function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code; function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code is use AWS.Messages; begin case Status is when 100 => return S100; when 101 => return S101; when 200 => return S200; when 201 => return S201; when 202 => return S202; when 301 => return S301; when 302 => return S302; when 400 => return S400; when 401 => return S401; when 402 => return S402; when 403 => return S403; when 404 => return S404; when others => return S500; end case; end To_Status_Code; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Resp : in Response; Process : not null access procedure (Name : in String; Value : in String)) is Headers : constant AWS.Headers.List := AWS.Response.Header (Resp.Data); begin AWS.Containers.Tables.Iterate_Names (AWS.Containers.Tables.Table_Type (Headers), ";", Process); end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Resp : in Response; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- ------------------------------ -- Sets a response header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ procedure Set_Header (Resp : in out Response; Name : in String; Value : in String) is begin if AWS.Response.Header (Resp.Data, Name)'Length = 0 then AWS.Response.Set.Add_Header (D => Resp.Data, Name => Name, Value => Value); end if; end Set_Header; -- ------------------------------ -- Adds a response header with the given name and value. -- This method allows response headers to have multiple values. -- ------------------------------ procedure Add_Header (Resp : in out Response; Name : in String; Value : in String) is begin AWS.Response.Set.Add_Header (D => Resp.Data, Name => Name, Value => Value); end Add_Header; -- ------------------------------ -- Sends a temporary redirect response to the client using the specified redirect -- location URL. This method can accept relative URLs; the servlet container must -- convert the relative URL to an absolute URL before sending the response to the -- client. If the location is relative without a leading '/' the container -- interprets it as relative to the current request URI. If the location is relative -- with a leading '/' the container interprets it as relative to the servlet -- container root. -- -- If the response has already been committed, this method throws an -- IllegalStateException. After using this method, the response should be -- considered to be committed and should not be written to. -- ------------------------------ procedure Send_Redirect (Resp : in out Response; Location : in String) is begin Response'Class (Resp).Set_Status (SC_FOUND); Response'Class (Resp).Set_Header (Name => "Location", Value => Location); Resp.Redirect := True; end Send_Redirect; -- ------------------------------ -- Prepare the response data by collecting the status, content type and message body. -- ------------------------------ procedure Build (Resp : in out Response) is begin if not Resp.Redirect then AWS.Response.Set.Content_Type (D => Resp.Data, Value => Resp.Get_Content_Type); Resp.Content.Flush; if AWS.Response.Is_Empty (Resp.Data) then AWS.Response.Set.Message_Body (Resp.Data, ""); end if; else AWS.Response.Set.Mode (D => Resp.Data, Value => AWS.Response.Header); end if; AWS.Response.Set.Status_Code (D => Resp.Data, Value => To_Status_Code (Resp.Get_Status)); end Build; -- ------------------------------ -- Get the response data -- ------------------------------ function Get_Data (Resp : in Response) return AWS.Response.Data is begin return Resp.Data; end Get_Data; end ASF.Responses.Web;
Update initialization of the output stream
Update initialization of the output stream
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
7ddc758aa01f29ccfae56e241d937643cd61bfd1
mat/src/mat-targets-probes.adb
mat/src/mat-targets-probes.adb
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ELF; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes"); M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; M_LIBNAME : constant MAT.Events.Internal_Reference := 6; M_LADDR : constant MAT.Events.Internal_Reference := 7; M_COUNT : constant MAT.Events.Internal_Reference := 8; M_TYPE : constant MAT.Events.Internal_Reference := 9; M_VADDR : constant MAT.Events.Internal_Reference := 10; M_SIZE : constant MAT.Events.Internal_Reference := 11; M_FLAGS : constant MAT.Events.Internal_Reference := 12; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; LIBNAME_NAME : aliased constant String := "libname"; LADDR_NAME : aliased constant String := "laddr"; COUNT_NAME : aliased constant String := "count"; TYPE_NAME : aliased constant String := "type"; VADDR_NAME : aliased constant String := "vaddr"; SIZE_NAME : aliased constant String := "size"; FLAGS_NAME : aliased constant String := "flags"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); Library_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => LIBNAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME), 2 => (Name => LADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_LADDR), 3 => (Name => COUNT_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_COUNT), 4 => (Name => TYPE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_TYPE), 5 => (Name => VADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_VADDR), 6 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_SIZE), 7 => (Name => FLAGS_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FLAGS)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Id : in MAT.Events.Targets.Probe_Index_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Addr; Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); end Probe_Begin; -- ------------------------------ -- Extract the information from the 'library' event. -- ------------------------------ procedure Probe_Library (Probe : in Process_Probe_Type; Id : in MAT.Events.Targets.Probe_Index_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Addr; Count : MAT.Types.Target_Size := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; Addr : MAT.Types.Target_Addr; Pos : Natural := Defs'Last + 1; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_COUNT => Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); Pos := I + 1; exit; when M_LIBNAME => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_LADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; for Region in 1 .. Count loop declare Region : MAT.Memory.Region_Info; Kind : ELF.Elf32_Word := 0; begin for I in Pos .. Defs'Last loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_VADDR => Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_TYPE => Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when M_FLAGS => Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; if Kind = ELF.PT_LOAD then Region.Start_Addr := Addr + Region.Start_Addr; Region.End_Addr := Region.Start_Addr + Region.Size; Region.Path := Path; Probe.Target.Process.Memory.Add_Region (Region); end if; end; end loop; end Probe_Library; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Events.Targets.Probe_Index_Type; begin if Event.Index = MAT.Events.Targets.MSG_BEGIN then Probe.Probe_Begin (Event.Index, Params.all, Msg); elsif Event.Index = MAT.Events.Targets.MSG_LIBRARY then Probe.Probe_Library (Event.Index, Params.all, Msg); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MAT.Events.Targets.MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MAT.Events.Targets.MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MAT.Events.Targets.MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ELF; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes"); M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; M_LIBNAME : constant MAT.Events.Internal_Reference := 6; M_LADDR : constant MAT.Events.Internal_Reference := 7; M_COUNT : constant MAT.Events.Internal_Reference := 8; M_TYPE : constant MAT.Events.Internal_Reference := 9; M_VADDR : constant MAT.Events.Internal_Reference := 10; M_SIZE : constant MAT.Events.Internal_Reference := 11; M_FLAGS : constant MAT.Events.Internal_Reference := 12; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; LIBNAME_NAME : aliased constant String := "libname"; LADDR_NAME : aliased constant String := "laddr"; COUNT_NAME : aliased constant String := "count"; TYPE_NAME : aliased constant String := "type"; VADDR_NAME : aliased constant String := "vaddr"; SIZE_NAME : aliased constant String := "size"; FLAGS_NAME : aliased constant String := "flags"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); Library_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => LIBNAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME), 2 => (Name => LADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_LADDR), 3 => (Name => COUNT_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_COUNT), 4 => (Name => TYPE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_TYPE), 5 => (Name => VADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_VADDR), 6 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_SIZE), 7 => (Name => FLAGS_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FLAGS)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Event.Addr := Heap.Start_Addr; Event.Size := Heap.Size; Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); end Probe_Begin; -- ------------------------------ -- Extract the information from the 'library' event. -- ------------------------------ procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Count : MAT.Types.Target_Size := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; Addr : MAT.Types.Target_Addr; Pos : Natural := Defs'Last + 1; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_COUNT => Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); Pos := I + 1; exit; when M_LIBNAME => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_LADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Event.Addr := Addr; Event.Size := 0; for Region in 1 .. Count loop declare Region : MAT.Memory.Region_Info; Kind : ELF.Elf32_Word := 0; begin for I in Pos .. Defs'Last loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_VADDR => Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_TYPE => Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when M_FLAGS => Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; if Kind = ELF.PT_LOAD then Region.Start_Addr := Addr + Region.Start_Addr; Region.End_Addr := Region.Start_Addr + Region.Size; Region.Path := Path; Event.Size := Event.Size + Region.Size; Probe.Target.Process.Memory.Add_Region (Region); end if; end; end loop; end Probe_Library; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Events.Targets.Probe_Index_Type; begin if Event.Index = MAT.Events.Targets.MSG_BEGIN then Probe.Probe_Begin (Params.all, Msg, Event); elsif Event.Index = MAT.Events.Targets.MSG_LIBRARY then Probe.Probe_Library (Params.all, Msg, Event); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MAT.Events.Targets.MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MAT.Events.Targets.MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MAT.Events.Targets.MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
Update the event associated with the begin and library event to keep track of the library mapped address and size in the event
Update the event associated with the begin and library event to keep track of the library mapped address and size in the event
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d2e89ea940b97ad9677faca24cc4b24e5b93f472
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 Util.Log.Loggers; with GNAT.Sockets; with Readline; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; with MAT.Readers.Streams.Sockets; procedure Matp is procedure Interactive_Loop is Target : MAT.Targets.Target_Type; Console : aliased MAT.Consoles.Text.Console_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; Address : GNAT.Sockets.Sock_Addr_Type; begin Target.Console (Console'Unchecked_Access); Address.Addr := GNAT.Sockets.Any_Inet_Addr; Address.Port := 4096; Server.Start (Address); loop declare Line : constant String := Readline.Get_Line ("matp>"); begin MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; Server.Stop; exception when Ada.IO_Exceptions.End_Error => Server.Stop; return; end Interactive_Loop; begin Util.Log.Loggers.Initialize ("matp.properties"); 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 Util.Log.Loggers; with GNAT.Sockets; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; with MAT.Readers.Streams.Sockets; procedure Matp is Target : MAT.Targets.Target_Type; Console : aliased MAT.Consoles.Text.Console_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; Address : GNAT.Sockets.Sock_Addr_Type; begin Util.Log.Loggers.Initialize ("matp.properties"); Target.Console (Console'Unchecked_Access); Address.Addr := GNAT.Sockets.Any_Inet_Addr; Address.Port := 4096; Server.Start (Address); MAT.Commands.Interactive (Target); Server.Stop; exception when Ada.IO_Exceptions.End_Error => Server.Stop; end Matp;
Use the Interactive procedure to simplify the Matp procedure
Use the Interactive procedure to simplify the Matp procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d132692f0a4ed7253b5c6fa450a818fe52905430
src/sys/os-windows/util-processes-os.adb
src/sys/os-windows/util-processes-os.adb
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 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 System; with Ada.Unchecked_Deallocation; with Ada.Characters.Conversions; with Util.Log.Loggers; package body Util.Processes.Os is use type Interfaces.C.size_t; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Os"); -- ------------------------------ -- Wait for the process to exit. -- ------------------------------ overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is use type Util.Streams.Output_Stream_Access; Result : DWORD; T : DWORD; Code : aliased DWORD; Status : BOOL; begin -- Close the input stream pipe if there is one. if Proc.Input /= null then Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close; end if; if Timeout < 0.0 then T := DWORD'Last; else T := DWORD (Timeout * 1000.0); end if; Log.Debug ("Waiting {0}", DWORD'Image (T)); Result := Wait_For_Single_Object (H => Sys.Process_Info.hProcess, Time => T); Log.Debug ("Status {0}", DWORD'Image (Result)); Status := Get_Exit_Code_Process (Proc => Sys.Process_Info.hProcess, Code => Code'Unchecked_Access); if Status = 0 then Log.Error ("Process is still running. Error {0}", Integer'Image (Get_Last_Error)); end if; Proc.Exit_Value := Integer (Code); Log.Debug ("Process exit is: {0}", Integer'Image (Proc.Exit_Value)); 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. -- ------------------------------ overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15) is Result : Integer; begin Result := Terminate_Process (Sys.Process_Info.hProcess, DWORD (Signal)); end Stop; -- Spawn a new process. overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE) is use Util.Streams.Raw; use Ada.Characters.Conversions; use Interfaces.C; use type System.Address; Result : Integer; Startup : aliased Startup_Info; R : BOOL; begin -- Since checks are disabled, verify by hand that the argv table is correct. if Sys.Command = null or else Sys.Command'Length < 1 then raise Program_Error with "Invalid process argument list"; end if; Startup.cb := Startup'Size / 8; Startup.hStdInput := Get_Std_Handle (STD_INPUT_HANDLE); Startup.hStdOutput := Get_Std_Handle (STD_OUTPUT_HANDLE); Startup.hStdError := Get_Std_Handle (STD_ERROR_HANDLE); if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then Build_Output_Pipe (Proc, Startup); end if; if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then Build_Input_Pipe (Proc, Startup); end if; -- Start the child process. Result := Create_Process (System.Null_Address, Sys.Command.all'Address, null, null, True, 16#0#, System.Null_Address, System.Null_Address, Startup'Unchecked_Access, Sys.Process_Info'Unchecked_Access); -- Close the handles which are not necessary. if Startup.hStdInput /= Get_Std_Handle (STD_INPUT_HANDLE) then R := Close_Handle (Startup.hStdInput); end if; if Startup.hStdOutput /= Get_Std_Handle (STD_OUTPUT_HANDLE) then R := Close_Handle (Startup.hStdOutput); end if; if Startup.hStdError /= Get_Std_Handle (STD_ERROR_HANDLE) then R := Close_Handle (Startup.hStdError); end if; if Result /= 1 then Result := Get_Last_Error; Log.Error ("Process creation failed: {0}", Integer'Image (Result)); raise Process_Error with "Cannot create process"; end if; Proc.Pid := Process_Identifier (Sys.Process_Info.dwProcessId); end Spawn; -- ------------------------------ -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. -- ------------------------------ function Create_Stream (File : in Util.Streams.Raw.File_Type) return Util.Streams.Raw.Raw_Stream_Access is Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream; begin Stream.Initialize (File); return Stream; end Create_Stream; -- ------------------------------ -- Build the output pipe redirection to read the process output. -- ------------------------------ procedure Build_Output_Pipe (Proc : in out Process'Class; Into : in out Startup_Info) is Sec : aliased Security_Attributes; Read_Handle : aliased HANDLE; Write_Handle : aliased HANDLE; Read_Pipe_Handle : aliased HANDLE; Error_Handle : aliased HANDLE; Result : BOOL; Current_Proc : constant HANDLE := Get_Current_Process; begin Sec.Length := Sec'Size / 8; Sec.Inherit := True; Sec.Security_Descriptor := System.Null_Address; Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access, Write_Handle => Write_Handle'Unchecked_Access, Attributes => Sec'Unchecked_Access, Buf_Size => 0); if Result = 0 then Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error)); raise Program_Error with "Cannot create pipe"; end if; Result := Duplicate_Handle (SourceProcessHandle => Current_Proc, SourceHandle => Read_Handle, TargetProcessHandle => Current_Proc, TargetHandle => Read_Pipe_Handle'Unchecked_Access, DesiredAccess => 0, InheritHandle => 0, Options => 2); if Result = 0 then raise Program_Error with "Cannot create pipe"; end if; Result := Close_Handle (Read_Handle); Result := Duplicate_Handle (SourceProcessHandle => Current_Proc, SourceHandle => Write_Handle, TargetProcessHandle => Current_Proc, TargetHandle => Error_Handle'Unchecked_Access, DesiredAccess => 0, InheritHandle => 1, Options => 2); if Result = 0 then raise Program_Error with "Cannot create pipe"; end if; Into.dwFlags := 16#100#; Into.hStdOutput := Write_Handle; Into.hStdError := Error_Handle; Proc.Output := Create_Stream (Read_Pipe_Handle).all'Access; end Build_Output_Pipe; -- ------------------------------ -- Build the input pipe redirection to write the process standard input. -- ------------------------------ procedure Build_Input_Pipe (Proc : in out Process'Class; Into : in out Startup_Info) is Sec : aliased Security_Attributes; Read_Handle : aliased HANDLE; Write_Handle : aliased HANDLE; Write_Pipe_Handle : aliased HANDLE; Result : BOOL; Current_Proc : constant HANDLE := Get_Current_Process; begin Sec.Length := Sec'Size / 8; Sec.Inherit := True; Sec.Security_Descriptor := System.Null_Address; Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access, Write_Handle => Write_Handle'Unchecked_Access, Attributes => Sec'Unchecked_Access, Buf_Size => 0); if Result = 0 then Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error)); raise Program_Error with "Cannot create pipe"; end if; Result := Duplicate_Handle (SourceProcessHandle => Current_Proc, SourceHandle => Write_Handle, TargetProcessHandle => Current_Proc, TargetHandle => Write_Pipe_Handle'Unchecked_Access, DesiredAccess => 0, InheritHandle => 0, Options => 2); if Result = 0 then raise Program_Error with "Cannot create pipe"; end if; Result := Close_Handle (Write_Handle); Into.dwFlags := 16#100#; Into.hStdInput := Read_Handle; Proc.Input := Create_Stream (Write_Pipe_Handle).all'Access; end Build_Input_Pipe; procedure Free is new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array, Name => Wchar_Ptr); -- ------------------------------ -- Append the argument to the process argument list. -- ------------------------------ overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String) is Len : Interfaces.C.size_t := Arg'Length; begin if Sys.Command /= null then Len := Len + Sys.Command'Length + 2; declare S : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Len); begin S (Sys.Command'Range) := Sys.Command.all; Free (Sys.Command); Sys.Command := S; end; Sys.Command (Sys.Pos) := Interfaces.C.To_C (' '); Sys.Pos := Sys.Pos + 1; else Sys.Command := new Interfaces.C.wchar_array (0 .. Len + 1); Sys.Pos := 0; end if; for I in Arg'Range loop Sys.Command (Sys.Pos) := Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (Arg (I))); Sys.Pos := Sys.Pos + 1; end loop; Sys.Command (Sys.Pos) := Interfaces.C.wide_nul; end Append_Argument; -- ------------------------------ -- Set the process input, output and error streams to redirect and use specified files. -- ------------------------------ overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean; To_Close : in File_Type_Array_Access) is begin Sys.To_Close := To_Close; end Set_Streams; -- ------------------------------ -- Deletes the storage held by the system process. -- ------------------------------ overriding procedure Finalize (Sys : in out System_Process) is use type System.Address; Result : BOOL; pragma Unreferenced (Result); begin if Sys.Process_Info.hProcess /= NO_FILE then Result := Close_Handle (Sys.Process_Info.hProcess); Sys.Process_Info.hProcess := NO_FILE; end if; if Sys.Process_Info.hThread /= NO_FILE then Result := Close_Handle (Sys.Process_Info.hThread); Sys.Process_Info.hThread := NO_FILE; end if; Free (Sys.Command); end Finalize; end Util.Processes.Os;
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Ada.Unchecked_Deallocation; with Ada.Characters.Conversions; with Util.Log.Loggers; package body Util.Processes.Os is use type Interfaces.C.size_t; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Os"); procedure Free is new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array, Name => Wchar_Ptr); function To_WSTR (Value : in String) return Wchar_Ptr; -- ------------------------------ -- Wait for the process to exit. -- ------------------------------ overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is use type Util.Streams.Output_Stream_Access; Result : DWORD; T : DWORD; Code : aliased DWORD; Status : BOOL; begin -- Close the input stream pipe if there is one. if Proc.Input /= null then Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close; end if; if Timeout < 0.0 then T := DWORD'Last; else T := DWORD (Timeout * 1000.0); end if; Log.Debug ("Waiting {0}", DWORD'Image (T)); Result := Wait_For_Single_Object (H => Sys.Process_Info.hProcess, Time => T); Log.Debug ("Status {0}", DWORD'Image (Result)); Status := Get_Exit_Code_Process (Proc => Sys.Process_Info.hProcess, Code => Code'Unchecked_Access); if Status = 0 then Log.Error ("Process is still running. Error {0}", Integer'Image (Get_Last_Error)); end if; Proc.Exit_Value := Integer (Code); Log.Debug ("Process exit is: {0}", Integer'Image (Proc.Exit_Value)); 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. -- ------------------------------ overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15) is pragma Unreferenced (Proc); Result : Integer; pragma Unreferenced (Result); begin Result := Terminate_Process (Sys.Process_Info.hProcess, DWORD (Signal)); end Stop; procedure Prepare_Working_Directory (Sys : in out System_Process; Proc : in out Process'Class) is Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir); begin Free (Sys.Dir); if Dir'Length > 0 then if not Ada.Directories.Exists (Dir) or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory then raise Ada.Directories.Name_Error with "Invalid directory: " & Dir; end if; Sys.Dir := To_WSTR (Dir); end if; end Prepare_Working_Directory; -- Spawn a new process. overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE) is use Util.Streams.Raw; use Ada.Characters.Conversions; use Interfaces.C; use type System.Address; Result : Integer; Startup : aliased Startup_Info; R : BOOL; begin Sys.Prepare_Working_Directory (Proc); -- Since checks are disabled, verify by hand that the argv table is correct. if Sys.Command = null or else Sys.Command'Length < 1 then raise Program_Error with "Invalid process argument list"; end if; Startup.cb := Startup'Size / 8; Startup.hStdInput := Get_Std_Handle (STD_INPUT_HANDLE); Startup.hStdOutput := Get_Std_Handle (STD_OUTPUT_HANDLE); Startup.hStdError := Get_Std_Handle (STD_ERROR_HANDLE); if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then Build_Output_Pipe (Proc, Startup); end if; if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then Build_Input_Pipe (Proc, Startup); end if; -- Start the child process. Result := Create_Process (System.Null_Address, Sys.Command.all'Address, null, null, True, 16#0#, System.Null_Address, Sys.Dir, Startup'Unchecked_Access, Sys.Process_Info'Unchecked_Access); -- Close the handles which are not necessary. if Startup.hStdInput /= Get_Std_Handle (STD_INPUT_HANDLE) then R := Close_Handle (Startup.hStdInput); end if; if Startup.hStdOutput /= Get_Std_Handle (STD_OUTPUT_HANDLE) then R := Close_Handle (Startup.hStdOutput); end if; if Startup.hStdError /= Get_Std_Handle (STD_ERROR_HANDLE) then R := Close_Handle (Startup.hStdError); end if; if Result /= 1 then Result := Get_Last_Error; Log.Error ("Process creation failed: {0}", Integer'Image (Result)); raise Process_Error with "Cannot create process"; end if; Proc.Pid := Process_Identifier (Sys.Process_Info.dwProcessId); end Spawn; -- ------------------------------ -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. -- ------------------------------ function Create_Stream (File : in Util.Streams.Raw.File_Type) return Util.Streams.Raw.Raw_Stream_Access is Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream; begin Stream.Initialize (File); return Stream; end Create_Stream; -- ------------------------------ -- Build the output pipe redirection to read the process output. -- ------------------------------ procedure Build_Output_Pipe (Proc : in out Process'Class; Into : in out Startup_Info) is Sec : aliased Security_Attributes; Read_Handle : aliased HANDLE; Write_Handle : aliased HANDLE; Read_Pipe_Handle : aliased HANDLE; Error_Handle : aliased HANDLE; Result : BOOL; Current_Proc : constant HANDLE := Get_Current_Process; begin Sec.Length := Sec'Size / 8; Sec.Inherit := True; Sec.Security_Descriptor := System.Null_Address; Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access, Write_Handle => Write_Handle'Unchecked_Access, Attributes => Sec'Unchecked_Access, Buf_Size => 0); if Result = 0 then Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error)); raise Program_Error with "Cannot create pipe"; end if; Result := Duplicate_Handle (SourceProcessHandle => Current_Proc, SourceHandle => Read_Handle, TargetProcessHandle => Current_Proc, TargetHandle => Read_Pipe_Handle'Unchecked_Access, DesiredAccess => 0, InheritHandle => 0, Options => 2); if Result = 0 then raise Program_Error with "Cannot create pipe"; end if; Result := Close_Handle (Read_Handle); Result := Duplicate_Handle (SourceProcessHandle => Current_Proc, SourceHandle => Write_Handle, TargetProcessHandle => Current_Proc, TargetHandle => Error_Handle'Unchecked_Access, DesiredAccess => 0, InheritHandle => 1, Options => 2); if Result = 0 then raise Program_Error with "Cannot create pipe"; end if; Into.dwFlags := 16#100#; Into.hStdOutput := Write_Handle; Into.hStdError := Error_Handle; Proc.Output := Create_Stream (Read_Pipe_Handle).all'Access; end Build_Output_Pipe; -- ------------------------------ -- Build the input pipe redirection to write the process standard input. -- ------------------------------ procedure Build_Input_Pipe (Proc : in out Process'Class; Into : in out Startup_Info) is Sec : aliased Security_Attributes; Read_Handle : aliased HANDLE; Write_Handle : aliased HANDLE; Write_Pipe_Handle : aliased HANDLE; Result : BOOL; Current_Proc : constant HANDLE := Get_Current_Process; begin Sec.Length := Sec'Size / 8; Sec.Inherit := True; Sec.Security_Descriptor := System.Null_Address; Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access, Write_Handle => Write_Handle'Unchecked_Access, Attributes => Sec'Unchecked_Access, Buf_Size => 0); if Result = 0 then Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error)); raise Program_Error with "Cannot create pipe"; end if; Result := Duplicate_Handle (SourceProcessHandle => Current_Proc, SourceHandle => Write_Handle, TargetProcessHandle => Current_Proc, TargetHandle => Write_Pipe_Handle'Unchecked_Access, DesiredAccess => 0, InheritHandle => 0, Options => 2); if Result = 0 then raise Program_Error with "Cannot create pipe"; end if; Result := Close_Handle (Write_Handle); Into.dwFlags := 16#100#; Into.hStdInput := Read_Handle; Proc.Input := Create_Stream (Write_Pipe_Handle).all'Access; end Build_Input_Pipe; -- ------------------------------ -- Append the argument to the process argument list. -- ------------------------------ overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String) is Len : Interfaces.C.size_t := Arg'Length; begin if Sys.Command /= null then Len := Len + Sys.Command'Length + 2; declare S : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Len); begin S (Sys.Command'Range) := Sys.Command.all; Free (Sys.Command); Sys.Command := S; end; Sys.Command (Sys.Pos) := Interfaces.C.To_C (' '); Sys.Pos := Sys.Pos + 1; else Sys.Command := new Interfaces.C.wchar_array (0 .. Len + 1); Sys.Pos := 0; end if; for I in Arg'Range loop Sys.Command (Sys.Pos) := Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (Arg (I))); Sys.Pos := Sys.Pos + 1; end loop; Sys.Command (Sys.Pos) := Interfaces.C.wide_nul; end Append_Argument; function To_WSTR (Value : in String) return Wchar_Ptr is Result : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Value'Length + 1); Pos : Interfaces.C.size_t := 0; begin for C of Value loop Result (Pos) := Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (C)); Pos := Pos + 1; end loop; Result (Pos) := Interfaces.C.wide_nul; return Result; end To_WSTR; -- ------------------------------ -- Set the process input, output and error streams to redirect and use specified files. -- ------------------------------ overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean; To_Close : in File_Type_Array_Access) is begin if Input'Length > 0 then Sys.In_File := To_WSTR (Input); end if; if Output'Length > 0 then Sys.Out_File := To_WSTR (Output); Sys.Out_Append := Append_Output; end if; if Error'Length > 0 then Sys.Err_File := To_WSTR (Error); Sys.Err_Append := Append_Error; end if; Sys.To_Close := To_Close; end Set_Streams; -- ------------------------------ -- Deletes the storage held by the system process. -- ------------------------------ overriding procedure Finalize (Sys : in out System_Process) is use type System.Address; Result : BOOL; pragma Unreferenced (Result); begin if Sys.Process_Info.hProcess /= NO_FILE then Result := Close_Handle (Sys.Process_Info.hProcess); Sys.Process_Info.hProcess := NO_FILE; end if; if Sys.Process_Info.hThread /= NO_FILE then Result := Close_Handle (Sys.Process_Info.hThread); Sys.Process_Info.hThread := NO_FILE; end if; Free (Sys.In_File); Free (Sys.Out_File); Free (Sys.Err_File); Free (Sys.Dir); Free (Sys.Command); end Finalize; end Util.Processes.Os;
Fix Set_Streams procedure to take into account redirection to/from a file Add Prepare_Working_Directory to setup the working directory of the process
Fix Set_Streams procedure to take into account redirection to/from a file Add Prepare_Working_Directory to setup the working directory of the process
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3042a9a228a534f808930147b000c5b357d2605a
src/util-beans-objects-maps.adb
src/util-beans-objects-maps.adb
----------------------------------------------------------------------- -- Util.Beans.Objects.Maps -- Object maps -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Beans.Objects.Maps is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : in Map_Bean; Name : in String) return Object is Pos : constant Cursor := From.Find (Name); begin if Has_Element (Pos) then return Element (Pos); else return Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. -- ------------------------------ procedure Set_Value (From : in out Map_Bean; Name : in String; Value : in Object) is begin From.Include (Name, Value); end Set_Value; -- ------------------------------ -- Iterate over the members of the map. -- ------------------------------ procedure Iterate (From : in Object; Process : not null access procedure (Name : in String; Item : in Object)) is procedure Process_One (Pos : in Maps.Cursor); procedure Process_One (Pos : in Maps.Cursor) is begin Process (Maps.Key (Pos), Maps.Element (Pos)); end Process_One; Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (From); begin if Bean /= null and then Bean.all in Util.Beans.Objects.Maps.Map_Bean'Class then Map_Bean'Class (Bean.all).Iterate (Process_One'Access); end if; end Iterate; -- ------------------------------ -- Create an object that contains a <tt>Map_Bean</tt> instance. -- ------------------------------ function Create return Object is M : constant access Map_Bean'Class := new Map_Bean; begin return To_Object (Value => M, Storage => DYNAMIC); end Create; end Util.Beans.Objects.Maps;
----------------------------------------------------------------------- -- util-beans-objects-maps -- Object maps -- Copyright (C) 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Beans.Objects.Maps is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : in Map_Bean; Name : in String) return Object is Pos : constant Cursor := From.Find (Name); begin if Has_Element (Pos) then return Element (Pos); else return Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. -- ------------------------------ procedure Set_Value (From : in out Map_Bean; Name : in String; Value : in Object) is begin From.Include (Name, Value); end Set_Value; -- ------------------------------ -- Iterate over the members of the map. -- ------------------------------ procedure Iterate (From : in Object; Process : not null access procedure (Name : in String; Item : in Object)) is procedure Process_One (Pos : in Maps.Cursor); procedure Process_One (Pos : in Maps.Cursor) is begin Process (Maps.Key (Pos), Maps.Element (Pos)); end Process_One; Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (From); begin if Bean /= null and then Bean.all in Util.Beans.Objects.Maps.Map_Bean'Class then Map_Bean'Class (Bean.all).Iterate (Process_One'Access); end if; end Iterate; -- ------------------------------ -- Create an object that contains a <tt>Map_Bean</tt> instance. -- ------------------------------ function Create return Object is M : constant access Map_Bean'Class := new Map_Bean; begin return To_Object (Value => M, Storage => DYNAMIC); end Create; end Util.Beans.Objects.Maps;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ba44cc5ab476dc8486762133b21b2a10271485ca
src/sys/encoders/util-encoders-hmac-sha256.ads
src/sys/encoders/util-encoders-hmac-sha256.ads
----------------------------------------------------------------------- -- util-encoders-hmac-sha256 -- Compute HMAC-SHA256 authentication code -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Util.Encoders.SHA256; -- The <b>Util.Encodes.HMAC.SHA256</b> package generates HMAC-SHA256 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package Util.Encoders.HMAC.SHA256 is HASH_SIZE : constant := Util.Encoders.SHA256.HASH_SIZE; -- Sign the data string with the key and return the HMAC-SHA256 code in binary. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Hash_Array; -- Sign the data string with the key and return the HMAC-SHA256 code as hexadecimal string. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Digest; -- Sign the data array with the key and return the HMAC-SHA256 code in the result. procedure Sign (Key : in Ada.Streams.Stream_Element_Array; Data : in Ada.Streams.Stream_Element_Array; Result : out Util.Encoders.SHA256.Hash_Array); procedure Sign (Key : in Secret_Key; Data : in Ada.Streams.Stream_Element_Array; Result : out Util.Encoders.SHA256.Hash_Array); -- Sign the data string with the key and return the HMAC-SHA256 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.SHA256.Base64_Digest; -- ------------------------------ -- HMAC-SHA256 Context -- ------------------------------ type Context is limited private; -- 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); -- 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); -- Update the hash with the string. procedure Update (E : in out Context; S : in String); -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array); -- Computes the HMAC-SHA256 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.SHA256.Hash_Array); -- Computes the HMAC-SHA256 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.SHA256.Digest); -- Computes the HMAC-SHA256 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.SHA256.Base64_Digest; URL : in Boolean := False); private type Context is new Ada.Finalization.Limited_Controlled with record SHA : Util.Encoders.SHA256.Context; Key : Ada.Streams.Stream_Element_Array (0 .. 63); Key_Len : Ada.Streams.Stream_Element_Offset; end record; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context); end Util.Encoders.HMAC.SHA256;
----------------------------------------------------------------------- -- util-encoders-hmac-sha256 -- Compute HMAC-SHA256 authentication code -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Util.Encoders.SHA256; -- The <b>Util.Encodes.HMAC.SHA256</b> package generates HMAC-SHA256 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package Util.Encoders.HMAC.SHA256 is HASH_SIZE : constant := Util.Encoders.SHA256.HASH_SIZE; -- Sign the data string with the key and return the HMAC-SHA256 code in binary. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Hash_Array; -- Sign the data string with the key and return the HMAC-SHA256 code as hexadecimal string. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Digest; -- Sign the data array with the key and return the HMAC-SHA256 code in the result. procedure Sign (Key : in Ada.Streams.Stream_Element_Array; Data : in Ada.Streams.Stream_Element_Array; Result : out Util.Encoders.SHA256.Hash_Array); procedure Sign (Key : in Secret_Key; Data : in Ada.Streams.Stream_Element_Array; Result : out Util.Encoders.SHA256.Hash_Array); -- Sign the data string with the key and return the HMAC-SHA256 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.SHA256.Base64_Digest; -- ------------------------------ -- HMAC-SHA256 Context -- ------------------------------ type Context is limited private; -- 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); -- 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); procedure Set_Key (E : in out Context; Key : in Secret_Key); -- Update the hash with the string. procedure Update (E : in out Context; S : in String); -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array); -- Update the hash with the secret key. procedure Update (E : in out Context; S : in Secret_Key); -- Computes the HMAC-SHA256 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.SHA256.Hash_Array); -- Computes the HMAC-SHA256 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.SHA256.Digest); -- Computes the HMAC-SHA256 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.SHA256.Base64_Digest; URL : in Boolean := False); private type Context is new Ada.Finalization.Limited_Controlled with record SHA : Util.Encoders.SHA256.Context; Key : Ada.Streams.Stream_Element_Array (0 .. 63); Key_Len : Ada.Streams.Stream_Element_Offset; end record; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context); end Util.Encoders.HMAC.SHA256;
Add Set_Key and Update using a Secret_Key object
Add Set_Key and Update using a Secret_Key object
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
00d7c792c2a66d2bcbe9e9adec3c5a57815d6d56
mat/src/mat-readers-streams-sockets.adb
mat/src/mat-readers-streams-sockets.adb
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- 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 Util.Log.Loggers; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Initialize the socket listener. -- ------------------------------ overriding procedure Initialize (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Create_Selector (Listener.Accept_Selector); end Initialize; -- ------------------------------ -- Destroy the socket listener. -- ------------------------------ overriding procedure Finalize (Listener : in out Socket_Listener_Type) is use type GNAT.Sockets.Selector_Type; begin GNAT.Sockets.Close_Selector (Listener.Accept_Selector); end Finalize; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.Listener.Start (Listener'Unchecked_Access, Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; -- ------------------------------ -- Create a target instance for the new client. -- ------------------------------ procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is Reader : constant Socket_Reader_Type_Access := new Socket_Reader_Type; begin Reader.Server.Start (Reader, Client); end Create_Target; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; use type GNAT.Sockets.Selector_Status; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Listener_Type_Access; Client : GNAT.Sockets.Socket_Type; Selector_Status : GNAT.Sockets.Selector_Status; begin select accept Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := Listener; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; loop GNAT.Sockets.Accept_Socket (Server => Server, Socket => Client, Address => Peer, Timeout => GNAT.Sockets.Forever, Selector => Instance.Accept_Selector'Access, Status => Selector_Status); exit when Selector_Status = GNAT.Sockets.Aborted; if Selector_Status = GNAT.Sockets.Completed then Instance.Create_Target (Client => Client, Address => Peer); GNAT.Sockets.Close_Socket (Client); end if; end loop; GNAT.Sockets.Close_Socket (Server); end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; begin select accept Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type) do Instance := Reader; Socket := Client; end Start; or terminate; end select; Instance.Socket.Open (Socket); Instance.Read_All; GNAT.Sockets.Close_Socket (Socket); exception when E : others => Log.Error ("Exception", E); GNAT.Sockets.Close_Socket (Socket); end Socket_Reader_Task; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- 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 Util.Log.Loggers; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Initialize the socket listener. -- ------------------------------ overriding procedure Initialize (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Create_Selector (Listener.Accept_Selector); end Initialize; -- ------------------------------ -- Destroy the socket listener. -- ------------------------------ overriding procedure Finalize (Listener : in out Socket_Listener_Type) is use type GNAT.Sockets.Selector_Type; begin GNAT.Sockets.Close_Selector (Listener.Accept_Selector); end Finalize; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.Listener.Start (Listener'Unchecked_Access, Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; -- ------------------------------ -- Create a target instance for the new client. -- ------------------------------ procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is Reader : constant Socket_Reader_Type_Access := new Socket_Reader_Type; begin Reader.Client := Client; Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.Socket'Unchecked_Access, Output => null); Reader.Server.Start (Reader, Client); Listener.Clients.Append (Reader); end Create_Target; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; use type GNAT.Sockets.Selector_Status; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Listener_Type_Access; Client : GNAT.Sockets.Socket_Type; Selector_Status : GNAT.Sockets.Selector_Status; begin select accept Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := Listener; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; loop GNAT.Sockets.Accept_Socket (Server => Server, Socket => Client, Address => Peer, Timeout => GNAT.Sockets.Forever, Selector => Instance.Accept_Selector'Access, Status => Selector_Status); exit when Selector_Status = GNAT.Sockets.Aborted; if Selector_Status = GNAT.Sockets.Completed then Instance.Create_Target (Client => Client, Address => Peer); GNAT.Sockets.Close_Socket (Client); end if; end loop; GNAT.Sockets.Close_Socket (Server); end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; begin select accept Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type) do Instance := Reader; Socket := Client; end Start; or terminate; end select; Instance.Socket.Open (Socket); Instance.Read_All; GNAT.Sockets.Close_Socket (Socket); exception when E : others => Log.Error ("Exception", E); GNAT.Sockets.Close_Socket (Socket); end Socket_Reader_Task; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
Initialize the buffer stream when the client socket is created Add the new client in the list of clients
Initialize the buffer stream when the client socket is created Add the new client in the list of clients
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d10c7da72fddab92a1bf16b4b06f6c4d9100ff1f
mat/src/mat-readers-streams-sockets.adb
mat/src/mat-readers-streams-sockets.adb
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- 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 MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Initialize the socket listener. -- ------------------------------ overriding procedure Initialize (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Create_Selector (Listener.Accept_Selector); end Initialize; -- ------------------------------ -- Destroy the socket listener. -- ------------------------------ overriding procedure Finalize (Listener : in out Socket_Listener_Type) is use type GNAT.Sockets.Selector_Type; begin GNAT.Sockets.Close_Selector (Listener.Accept_Selector); end Finalize; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; List : in MAT.Readers.Reader_List_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.List := List; Listener.Listener.Start (Listener'Unchecked_Access, Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; -- ------------------------------ -- Create a target instance for the new client. -- ------------------------------ procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is Reader : constant Socket_Reader_Type_Access := new Socket_Reader_Type; begin Reader.Client := Client; Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.Socket'Unchecked_Access, Output => null); Reader.Server.Start (Reader, Client); Listener.List.Initialize (Reader.all); Listener.Clients.Append (Reader); end Create_Target; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; use type GNAT.Sockets.Selector_Status; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Listener_Type_Access; Client : GNAT.Sockets.Socket_Type; Selector_Status : GNAT.Sockets.Selector_Status; begin select accept Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := Listener; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; loop GNAT.Sockets.Accept_Socket (Server => Server, Socket => Client, Address => Peer, Timeout => GNAT.Sockets.Forever, Selector => Instance.Accept_Selector'Access, Status => Selector_Status); exit when Selector_Status = GNAT.Sockets.Aborted; if Selector_Status = GNAT.Sockets.Completed then Instance.Create_Target (Client => Client, Address => Peer); end if; end loop; GNAT.Sockets.Close_Socket (Server); declare Iter : Socket_Client_Lists.Cursor := Instance.Clients.First; begin while Socket_Client_Lists.Has_Element (Iter) loop GNAT.Sockets.Close_Socket (Socket_Client_Lists.Element (Iter).Client); Iter := Socket_Client_Lists.Next (Iter); end loop; end; end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; begin select accept Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type) do Instance := Reader; Socket := Client; end Start; or terminate; end select; Instance.Socket.Open (Socket); Instance.Read_All; GNAT.Sockets.Close_Socket (Socket); exception when E : others => Log.Error ("Exception", E, True); GNAT.Sockets.Close_Socket (Socket); end Socket_Reader_Task; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- 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 MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Initialize the socket listener. -- ------------------------------ overriding procedure Initialize (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Create_Selector (Listener.Accept_Selector); end Initialize; -- ------------------------------ -- Destroy the socket listener. -- ------------------------------ overriding procedure Finalize (Listener : in out Socket_Listener_Type) is use type GNAT.Sockets.Selector_Type; begin GNAT.Sockets.Close_Selector (Listener.Accept_Selector); end Finalize; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; List : in MAT.Events.Probes.Reader_List_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.List := List; Listener.Listener.Start (Listener'Unchecked_Access, Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; -- ------------------------------ -- Create a target instance for the new client. -- ------------------------------ procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is Reader : constant Socket_Reader_Type_Access := new Socket_Reader_Type; begin Reader.Client := Client; Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.Socket'Unchecked_Access, Output => null); Reader.Server.Start (Reader, Client); Listener.List.Initialize (Reader.all); Listener.Clients.Append (Reader); end Create_Target; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; use type GNAT.Sockets.Selector_Status; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Listener_Type_Access; Client : GNAT.Sockets.Socket_Type; Selector_Status : GNAT.Sockets.Selector_Status; begin select accept Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := Listener; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; loop GNAT.Sockets.Accept_Socket (Server => Server, Socket => Client, Address => Peer, Timeout => GNAT.Sockets.Forever, Selector => Instance.Accept_Selector'Access, Status => Selector_Status); exit when Selector_Status = GNAT.Sockets.Aborted; if Selector_Status = GNAT.Sockets.Completed then Instance.Create_Target (Client => Client, Address => Peer); end if; end loop; GNAT.Sockets.Close_Socket (Server); declare Iter : Socket_Client_Lists.Cursor := Instance.Clients.First; begin while Socket_Client_Lists.Has_Element (Iter) loop GNAT.Sockets.Close_Socket (Socket_Client_Lists.Element (Iter).Client); Iter := Socket_Client_Lists.Next (Iter); end loop; end; end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; begin select accept Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type) do Instance := Reader; Socket := Client; end Start; or terminate; end select; Instance.Socket.Open (Socket); Instance.Read_All; GNAT.Sockets.Close_Socket (Socket); exception when E : others => Log.Error ("Exception", E, True); GNAT.Sockets.Close_Socket (Socket); end Socket_Reader_Task; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
Fix the Start procedure definition
Fix the Start procedure definition
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
449a6ef15061164b32ced0d102e8caf88cac7adf
regtests/ado-queries-tests.adb
regtests/ado-queries-tests.adb
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with ADO.Drivers.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Query", Test_Set_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Limit", Test_Set_Limit'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Drivers.Connections; use type ADO.Drivers.Driver_Index; Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Manager, Config); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end; if Mysql_Driver /= null and then Manager.Driver = Mysql_Driver.Get_Driver_Index then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index' (MySQL driver)"); end; end if; if Sqlite_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index' (SQLite driver)"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is use ADO.Drivers.Connections; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; Info : Query_Info_Ref.Ref; begin -- Configure and load the XML queries. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (not Simple_Query.Query.Query.Get.Is_Null, "The simple query was not loaded"); -- T.Assert (not Index_Query.Query.Query.Get.Is_Null, "The index query was not loaded"); -- Info := Simple_Query.Query.Query.Get; -- Re-configure but do not reload. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (Info.Value = Simple_Query.Query.Query.Get.Value, -- "The simple query instance was not changed"); -- Configure again and reload. The query info must have changed. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (Info.Value /= Simple_Query.Query.Query.Get.Value, -- "The simple query instance was not changed"); -- Due to the reference held by 'Info', it refers to the data loaded first. -- T.Assert (Length (Info.Value.Main_Query (0).SQL) > 0, "The old query is not valid"); end Test_Initialize; -- ------------------------------ -- Test the Set_Query operation. -- ------------------------------ procedure Test_Set_Query (T : in out Test) is Query : ADO.Queries.Context; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Manager : Query_Manager; Config : ADO.Drivers.Connections.Configuration; begin ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("simple-query"); declare SQL : constant String := Query.Get_SQL (Manager); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; end Test_Set_Query; -- ------------------------------ -- Test the Set_Limit operation. -- ------------------------------ procedure Test_Set_Limit (T : in out Test) is Query : ADO.Queries.Context; begin Query.Set_Query ("index"); Query.Set_Limit (0, 10); Assert_Equals (T, 0, Query.Get_First_Row_Index, "Invalid first row index"); Assert_Equals (T, 10, Query.Get_Last_Row_Index, "Invalid last row index"); end Test_Set_Limit; end ADO.Queries.Tests;
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with ADO.Drivers.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Find_Query", Test_Find_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Query", Test_Set_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Limit", Test_Set_Limit'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Drivers.Connections; use type ADO.Drivers.Driver_Index; Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Manager, Config); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end; if Mysql_Driver /= null and then Manager.Driver = Mysql_Driver.Get_Driver_Index then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index' (MySQL driver)"); end; end if; if Sqlite_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index' (SQLite driver)"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is use ADO.Drivers.Connections; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; Info : Query_Info_Ref.Ref; begin -- Configure and load the XML queries. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (not Simple_Query.Query.Query.Get.Is_Null, "The simple query was not loaded"); -- T.Assert (not Index_Query.Query.Query.Get.Is_Null, "The index query was not loaded"); -- Info := Simple_Query.Query.Query.Get; -- Re-configure but do not reload. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (Info.Value = Simple_Query.Query.Query.Get.Value, -- "The simple query instance was not changed"); -- Configure again and reload. The query info must have changed. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (Info.Value /= Simple_Query.Query.Query.Get.Value, -- "The simple query instance was not changed"); -- Due to the reference held by 'Info', it refers to the data loaded first. -- T.Assert (Length (Info.Value.Main_Query (0).SQL) > 0, "The old query is not valid"); end Test_Initialize; -- ------------------------------ -- Test the Set_Query operation. -- ------------------------------ procedure Test_Set_Query (T : in out Test) is Query : ADO.Queries.Context; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Manager : Query_Manager; Config : ADO.Drivers.Connections.Configuration; begin ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("simple-query"); declare SQL : constant String := Query.Get_SQL (Manager); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; end Test_Set_Query; -- ------------------------------ -- Test the Set_Limit operation. -- ------------------------------ procedure Test_Set_Limit (T : in out Test) is Query : ADO.Queries.Context; begin Query.Set_Query ("index"); Query.Set_Limit (0, 10); Assert_Equals (T, 0, Query.Get_First_Row_Index, "Invalid first row index"); Assert_Equals (T, 10, Query.Get_Last_Row_Index, "Invalid last row index"); end Test_Set_Limit; -- ------------------------------ -- Test the Find_Query operation. -- ------------------------------ procedure Test_Find_Query (T : in out Test) is Q : Query_Definition_Access; begin Q := ADO.Queries.Loaders.Find_Query ("this query does not exist"); T.Assert (Q = null, "Find_Query should return null for unkown query"); end Test_Find_Query; end ADO.Queries.Tests;
Implement the Test_Find_Query test
Implement the Test_Find_Query test
Ada
apache-2.0
stcarrez/ada-ado
2854ff3115bf5f3a1e4b35621ea045b26679a113
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 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;
----------------------------------------------------------------------- -- 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 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;
Change Auth_Manager type to be a tagged type and not be abstract
Change Auth_Manager type to be a tagged type and not be abstract
Ada
apache-2.0
stcarrez/ada-security
8c818e627e853431c1e8362a0bedb721c71a5511
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Unbounded; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with GNAT.Regexp; with Security.Controllers; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop -- Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is use Ada.Strings.Unbounded; use Security.Controllers; procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in Policy_Config); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in Policy_Config) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Manager.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config, Element_Type_Access => Policy_Config_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Policy_Config_Access := new Policy_Config; begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Config.Manager := Policy'Unchecked_Access; Policy_Mapper.Set_Context (Reader, Config); end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Policy_Mapping.Add_Mapping ("policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Unbounded; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with GNAT.Regexp; with Security.Controllers; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop -- Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is use Ada.Strings.Unbounded; use Security.Controllers; procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in Policy_Config); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in Policy_Config) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Manager.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config, Element_Type_Access => Policy_Config_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Policy_Config_Access := new Policy_Config; begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Config.Manager := Policy'Unchecked_Access; Policy_Mapper.Set_Context (Reader, Config); end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
Change the URL policy configuration to <url-policy>...</url-policy>
Change the URL policy configuration to <url-policy>...</url-policy>
Ada
apache-2.0
Letractively/ada-security
b550f39b702d17d12fbfd5c6776f23d73bead5cc
mat/src/mat-readers.adb
mat/src/mat-readers.adb
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Events; with MAT.Types; with MAT.Readers.Marshaller; with Interfaces; package body MAT.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers"); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- 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) is Handler : Message_Handler; begin Handler.For_Servant := Reader; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Readers.Insert (Name, Handler); end Register_Reader; procedure Read_Probe (Client : in out Manager_Base; Msg : in out Message) is use type Interfaces.Unsigned_64; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : access MAT.Events.Frame_Info := Client.Frame; begin Frame.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_THREAD_ID => Frame.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind)); when P_FRAME_PC => for I in 1 .. Natural (Count) loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); end if; end loop; when others => null; end case; end; end loop; Frame.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32); Frame.Time := Frame.Time or Interfaces.Unsigned_64 (Time_Usec); Frame.Cur_Depth := Count; end Read_Probe; procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message) is use type MAT.Events.Attribute_Table_Ptr; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Message_Handler := Handler_Maps.Element (Pos); begin Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Client.Frame.all, Msg); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E); end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name); Frame : Message_Handler; procedure Add_Handler (Key : in String; Element : in out Message_Handler) is begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0}", Name); if Name = "begin" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Message_Handler) is use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Reader_Maps.Has_Element (Pos) then Client.Readers.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("begin", Frame); end if; end; end loop; if Reader_Maps.Has_Element (Pos) then Client.Readers.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- 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) is Count : MAT.Types.Uint16; begin Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; Client.Frame := new MAT.Events.Frame_Info (512); exception when E : others => Log.Error ("Exception while reading headers ", E); end Read_Headers; 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 Util.Log.Loggers; with MAT.Events; with MAT.Types; with MAT.Readers.Marshaller; with Interfaces; package body MAT.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers"); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC), 7 => (Name => RUSAGE_MINFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MINFLT), 8 => (Name => RUSAGE_MAJFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MAJFLT), 9 => (Name => RUSAGE_NVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NVCSW), 10 => (Name => RUSAGE_NIVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NIVCSW) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- 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) is Handler : Message_Handler; begin Handler.For_Servant := Reader; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Readers.Insert (Name, Handler); end Register_Reader; procedure Read_Probe (Client : in out Manager_Base; Msg : in out Message) is use type Interfaces.Unsigned_64; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : access MAT.Events.Frame_Info := Client.Frame; begin Frame.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_THREAD_ID => Frame.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind)); when P_FRAME_PC => for I in 1 .. Natural (Count) loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); end if; end loop; when others => null; end case; end; end loop; Frame.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32); Frame.Time := Frame.Time or Interfaces.Unsigned_64 (Time_Usec); Frame.Cur_Depth := Count; end Read_Probe; procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message) is use type MAT.Events.Attribute_Table_Ptr; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Message_Handler := Handler_Maps.Element (Pos); begin Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Client.Frame.all, Msg); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E); end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name); Frame : Message_Handler; procedure Add_Handler (Key : in String; Element : in out Message_Handler) is begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0}", Name); if Name = "begin" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Message_Handler) is use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Reader_Maps.Has_Element (Pos) then Client.Readers.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("begin", Frame); end if; end; end loop; if Reader_Maps.Has_Element (Pos) then Client.Readers.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- 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) is Count : MAT.Types.Uint16; begin Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; Client.Frame := new MAT.Events.Frame_Info (512); exception when E : others => Log.Error ("Exception while reading headers ", E); end Read_Headers; end MAT.Readers;
Add the rusage probe information in the probe attributes definition
Add the rusage probe information in the probe attributes definition
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
7520fb8b8980de98af03fb39e33da76492ef6ef7
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- Get a printable representation of the email recipients. function Image (Recipients : in AWS.SMTP.Recipients) return String; -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is pragma Unreferenced (Kind); begin if Message.To = null then Message.To := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); begin To (Message.To'Range) := Message.To.all; Free (Message.To); Message.To := To; end; end if; Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in String) is begin Message.Content := To_Unbounded_String (Content); end Set_Body; -- ------------------------------ -- Get a printable representation of the email recipients. -- ------------------------------ function Image (Recipients : in AWS.SMTP.Recipients) return String is Result : Unbounded_String; begin for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; return To_String (Result); end Image; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if Message.To = null then return; end if; if Message.Manager.Enable then Log.Info ("Send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Message.To.all, Subject => To_String (Message.Subject), Message => To_String (Message.Content), Status => Result); else Log.Info ("Disable send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To); end Finalize; -- ------------------------------ -- Create a SMTP based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost"); Port : constant String := Props.Get (Name => "smtp.port", Default => "25"); User : constant String := Props.Get (Name => "smtp.user", Default => ""); Passwd : constant String := Props.Get (Name => "smtp.password", Default => ""); Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1"); Secure : constant String := Props.Get (Name => "smtp.ssl", Default => "0"); Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager; begin Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port); Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true"; Result.Secure := Secure = "1" or Secure = "yes" or Secure = "true"; if User'Length > 0 then Result.Creds := AWS.SMTP.Authentication.Plain.Initialize (User, Passwd); Result.Server := AWS.SMTP.Client.Initialize (Server_Name => Server, Port => Positive'Value (Port), Secure => Result.Secure, Credential => Result.Creds'Access); else Result.Server := AWS.SMTP.Client.Initialize (Server_Name => Server, Port => Positive'Value (Port), Secure => Result.Secure); end if; Result.Self := Result; 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- Get a printable representation of the email recipients. function Image (Recipients : in AWS.SMTP.Recipients) return String; -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is pragma Unreferenced (Kind); begin if Message.To = null then Message.To := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); begin To (Message.To'Range) := Message.To.all; Free (Message.To); Message.To := To; end; end if; Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in String) is begin Message.Content := To_Unbounded_String (Content); end Set_Body; -- ------------------------------ -- Get a printable representation of the email recipients. -- ------------------------------ function Image (Recipients : in AWS.SMTP.Recipients) return String is Result : Unbounded_String; begin for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; return To_String (Result); end Image; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if Message.To = null then return; end if; if Message.Manager.Enable then Log.Info ("Send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Message.To.all, Subject => To_String (Message.Subject), Message => To_String (Message.Content), Status => Result); else Log.Info ("Disable send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To); end Finalize; 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;
Use the Initialize procedure for the SMTP client initialization Let the Initialize procedure be a separate procedure whose implementation is selectable from the GNAT project file
Use the Initialize procedure for the SMTP client initialization Let the Initialize procedure be a separate procedure whose implementation is selectable from the GNAT project file
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
123c0ec77504252c8b0d20521af25afa3b42f320
orka/src/orka/interface/orka-rendering-framebuffers.ads
orka/src/orka/interface/orka-rendering-framebuffers.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Ada.Containers.Indefinite_Holders; with GL.Buffers; with GL.Objects.Framebuffers; with GL.Objects.Textures; with GL.Types.Colors; with Orka.Contexts; with Orka.Rendering.Buffers; with Orka.Rendering.Textures; package Orka.Rendering.Framebuffers is pragma Preelaborate; use GL.Types; use all type Rendering.Textures.Format_Kind; package FB renames GL.Objects.Framebuffers; package Textures renames GL.Objects.Textures; subtype Color_Attachment_Point is FB.Attachment_Point range FB.Color_Attachment_0 .. FB.Color_Attachment_15; type Use_Point_Array is array (Rendering.Framebuffers.Color_Attachment_Point) of Boolean; -- TODO Use as formal parameter in procedure Invalidate type Buffer_Values is record Color : Colors.Color := (0.0, 0.0, 0.0, 0.0); Depth : GL.Buffers.Depth := 1.0; Stencil : GL.Buffers.Stencil_Index := 0; end record; type Framebuffer (Default : Boolean) is tagged private; function Create_Framebuffer (Width, Height : Size; Samples : Size := 0) return Framebuffer with Post => not Create_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function Create_Default_Framebuffer (Width, Height : Natural) return Framebuffer with Post => Create_Default_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function Width (Object : Framebuffer) return Size; function Height (Object : Framebuffer) return Size; function Samples (Object : Framebuffer) return Size; function Image (Object : Framebuffer) return String; -- Return a description of the given framebuffer procedure Use_Framebuffer (Object : Framebuffer); -- Use the framebuffer during rendering -- -- The viewport is adjusted to the size of the framebuffer. procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values); -- Set the default values for the color buffers and depth and stencil -- buffers function Default_Values (Object : Framebuffer) return Buffer_Values; -- Return the current default values used when clearing the attached -- textures procedure Set_Read_Buffer (Object : Framebuffer; Buffer : GL.Buffers.Color_Buffer_Selector); -- Set the buffer to use when blitting to another framebuffer with -- procedure Resolve_To procedure Set_Draw_Buffers (Object : in out Framebuffer; Buffers : GL.Buffers.Color_Buffer_List); -- Set the buffers to use when drawing to output variables in a fragment -- shader, when calling procedure Clear, or when another framebuffer -- blits its read buffer to this framebuffer with procedure Resolve_To procedure Clear (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (others => True)); -- Clear the attached textures for which the mask is True using -- the default values set with Set_Default_Values -- -- For clearing to be effective, the following conditions must apply: -- -- - Write mask off -- - Rasterizer discard disabled -- - Scissor test off or scissor rectangle set to the desired region -- - Called procedure Set_Draw_Buffers with a list of attachments -- -- If a combined depth/stencil texture has been attached, the depth -- and stencil components can be cleared separately, but it may be -- faster to clear both components. procedure Invalidate (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits); -- Invalidate the attached textures for which the mask is True procedure Resolve_To (Object, Subject : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False)) with Pre => Object /= Subject and (Mask.Color or Mask.Depth or Mask.Stencil) and (if Object.Samples > 0 and Subject.Samples > 0 then Object.Samples = Subject.Samples); -- Copy one or more buffers, resolving multiple samples and scaling -- if necessary, from the source to the destination framebuffer -- -- If a buffer is specified in the mask, then the buffer should exist -- in both framebuffers, otherwise the buffer is not copied. Call -- Set_Read_Buffer and Set_Draw_Buffers to control which buffer is read -- from and which buffers are written to. -- -- Format of color buffers may differ and will be converted (if -- supported). Formats of depth and stencil buffers must match. -- -- Note: simultaneously resolving multiple samples and scaling -- of color buffers requires GL_EXT_framebuffer_multisample_blit_scaled. -- If this extension is not present, then two separate calls to this -- procedure are needed. procedure Attach (Object : in out Framebuffer; Texture : Textures.Texture; Attachment : Color_Attachment_Point := FB.Color_Attachment_0; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and (if Rendering.Textures.Get_Format_Kind (Texture.Internal_Format) = Color then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => (if Rendering.Textures.Get_Format_Kind (Texture.Internal_Format) = Color then Object.Has_Attachment (Attachment)); -- Attach the texture to an attachment point based on the internal -- format of the texture or to the given attachment point if the -- texture is color renderable -- -- The internal format of the texture must be valid for the given -- attachment point. -- -- If one of the attached textures is layered (3D, 1D/2D array, cube -- map [array], or 2D multisampled array), then all attachments must -- have the same kind. -- -- If the texture is layered and you want to attach a specific layer, -- then you must call the procedure Attach_Layer below instead. -- -- All attachments of the framebuffer must have the same amount of -- samples and they must all have fixed sample locations, or none of -- them must have them. procedure Attach_Layer (Object : in out Framebuffer; Texture : Textures.Texture; Attachment : FB.Attachment_Point; Layer : Natural; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and Texture.Layered and (if Attachment in Color_Attachment_Point then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach layer of " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => Object.Has_Attachment (Attachment); -- Attach the selected 1D/2D layer of the texture to the attachment point -- -- The internal format of the texture must be valid for the given -- attachment point. -- -- The texture must be layered (3D, 1D/2D array, cube -- map [array], or 2D multisampled array). procedure Detach (Object : in out Framebuffer; Attachment : FB.Attachment_Point) with Pre => not Object.Default, Post => not Object.Has_Attachment (Attachment); -- Detach any texture currently attached to the given attachment point function Has_Attachment (Object : Framebuffer; Attachment : FB.Attachment_Point) return Boolean; Framebuffer_Incomplete_Error : exception; private package Attachment_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => Textures.Texture, "=" => Textures."="); package Color_Buffer_List_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => GL.Buffers.Color_Buffer_List, "=" => GL.Buffers."="); type Attachment_Array is array (FB.Attachment_Point) of Attachment_Holder.Holder; type Framebuffer (Default : Boolean) is tagged record GL_Framebuffer : FB.Framebuffer; Attachments : Attachment_Array; Defaults : Buffer_Values; Draw_Buffers : Color_Buffer_List_Holder.Holder; Width, Height, Samples : Size; end record; end Orka.Rendering.Framebuffers;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Ada.Containers.Indefinite_Holders; with GL.Buffers; with GL.Objects.Framebuffers; with GL.Objects.Textures; with GL.Types.Colors; with Orka.Contexts; with Orka.Rendering.Buffers; with Orka.Rendering.Textures; package Orka.Rendering.Framebuffers is pragma Preelaborate; use GL.Types; use all type Rendering.Textures.Format_Kind; package FB renames GL.Objects.Framebuffers; package Textures renames GL.Objects.Textures; subtype Color_Attachment_Point is FB.Attachment_Point range FB.Color_Attachment_0 .. FB.Color_Attachment_7; type Use_Point_Array is array (Rendering.Framebuffers.Color_Attachment_Point) of Boolean; -- TODO Use as formal parameter in procedure Invalidate type Buffer_Values is record Color : Colors.Color := (0.0, 0.0, 0.0, 0.0); Depth : GL.Buffers.Depth := 1.0; Stencil : GL.Buffers.Stencil_Index := 0; end record; type Framebuffer (Default : Boolean) is tagged private; function Create_Framebuffer (Width, Height : Size; Samples : Size := 0) return Framebuffer with Post => not Create_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function Create_Default_Framebuffer (Width, Height : Natural) return Framebuffer with Post => Create_Default_Framebuffer'Result.Default; ----------------------------------------------------------------------------- function Width (Object : Framebuffer) return Size; function Height (Object : Framebuffer) return Size; function Samples (Object : Framebuffer) return Size; function Image (Object : Framebuffer) return String; -- Return a description of the given framebuffer procedure Use_Framebuffer (Object : Framebuffer); -- Use the framebuffer during rendering -- -- The viewport is adjusted to the size of the framebuffer. procedure Set_Default_Values (Object : in out Framebuffer; Values : Buffer_Values); -- Set the default values for the color buffers and depth and stencil -- buffers function Default_Values (Object : Framebuffer) return Buffer_Values; -- Return the current default values used when clearing the attached -- textures procedure Set_Read_Buffer (Object : Framebuffer; Buffer : GL.Buffers.Color_Buffer_Selector); -- Set the buffer to use when blitting to another framebuffer with -- procedure Resolve_To procedure Set_Draw_Buffers (Object : in out Framebuffer; Buffers : GL.Buffers.Color_Buffer_List); -- Set the buffers to use when drawing to output variables in a fragment -- shader, when calling procedure Clear, or when another framebuffer -- blits its read buffer to this framebuffer with procedure Resolve_To procedure Clear (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (others => True)); -- Clear the attached textures for which the mask is True using -- the default values set with Set_Default_Values -- -- For clearing to be effective, the following conditions must apply: -- -- - Write mask off -- - Rasterizer discard disabled -- - Scissor test off or scissor rectangle set to the desired region -- - Called procedure Set_Draw_Buffers with a list of attachments -- -- If a combined depth/stencil texture has been attached, the depth -- and stencil components can be cleared separately, but it may be -- faster to clear both components. procedure Invalidate (Object : Framebuffer; Mask : GL.Buffers.Buffer_Bits); -- Invalidate the attached textures for which the mask is True procedure Resolve_To (Object, Subject : Framebuffer; Mask : GL.Buffers.Buffer_Bits := (Color => True, others => False)) with Pre => Object /= Subject and (Mask.Color or Mask.Depth or Mask.Stencil) and (if Object.Samples > 0 and Subject.Samples > 0 then Object.Samples = Subject.Samples); -- Copy one or more buffers, resolving multiple samples and scaling -- if necessary, from the source to the destination framebuffer -- -- If a buffer is specified in the mask, then the buffer should exist -- in both framebuffers, otherwise the buffer is not copied. Call -- Set_Read_Buffer and Set_Draw_Buffers to control which buffer is read -- from and which buffers are written to. -- -- Format of color buffers may differ and will be converted (if -- supported). Formats of depth and stencil buffers must match. -- -- Note: simultaneously resolving multiple samples and scaling -- of color buffers requires GL_EXT_framebuffer_multisample_blit_scaled. -- If this extension is not present, then two separate calls to this -- procedure are needed. procedure Attach (Object : in out Framebuffer; Texture : Textures.Texture; Attachment : Color_Attachment_Point := FB.Color_Attachment_0; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and (if Rendering.Textures.Get_Format_Kind (Texture.Internal_Format) = Color then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => (if Rendering.Textures.Get_Format_Kind (Texture.Internal_Format) = Color then Object.Has_Attachment (Attachment)); -- Attach the texture to an attachment point based on the internal -- format of the texture or to the given attachment point if the -- texture is color renderable -- -- The internal format of the texture must be valid for the given -- attachment point. -- -- If one of the attached textures is layered (3D, 1D/2D array, cube -- map [array], or 2D multisampled array), then all attachments must -- have the same kind. -- -- If the texture is layered and you want to attach a specific layer, -- then you must call the procedure Attach_Layer below instead. -- -- All attachments of the framebuffer must have the same amount of -- samples and they must all have fixed sample locations, or none of -- them must have them. procedure Attach_Layer (Object : in out Framebuffer; Texture : Textures.Texture; Attachment : FB.Attachment_Point; Layer : Natural; Level : Textures.Mipmap_Level := 0) with Pre => (not Object.Default and Texture.Allocated and Texture.Layered and (if Attachment in Color_Attachment_Point then (Object.Width = Texture.Width (Level) and Object.Height = Texture.Height (Level)))) or else raise Constraint_Error with "Cannot attach layer of " & Rendering.Textures.Image (Texture, Level) & " to " & Object.Image, Post => Object.Has_Attachment (Attachment); -- Attach the selected 1D/2D layer of the texture to the attachment point -- -- The internal format of the texture must be valid for the given -- attachment point. -- -- The texture must be layered (3D, 1D/2D array, cube -- map [array], or 2D multisampled array). procedure Detach (Object : in out Framebuffer; Attachment : FB.Attachment_Point) with Pre => not Object.Default, Post => not Object.Has_Attachment (Attachment); -- Detach any texture currently attached to the given attachment point function Has_Attachment (Object : Framebuffer; Attachment : FB.Attachment_Point) return Boolean; Framebuffer_Incomplete_Error : exception; private package Attachment_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => Textures.Texture, "=" => Textures."="); package Color_Buffer_List_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => GL.Buffers.Color_Buffer_List, "=" => GL.Buffers."="); type Attachment_Array is array (FB.Attachment_Point) of Attachment_Holder.Holder; type Framebuffer (Default : Boolean) is tagged record GL_Framebuffer : FB.Framebuffer; Attachments : Attachment_Array; Defaults : Buffer_Values; Draw_Buffers : Color_Buffer_List_Holder.Holder; Width, Height, Samples : Size; end record; end Orka.Rendering.Framebuffers;
Reduce max number of framebuffer attachments to 8
orka: Reduce max number of framebuffer attachments to 8 No GPU supports more than 8 attachment points for color buffers, even though the GL specification defines 16 points. Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
422e2a612672f4ad488fb2208a7932fba2b91f7d
awa/samples/src/atlas-applications.ads
awa/samples/src/atlas-applications.ads
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- 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 ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Filters.Dump; with ASF.Servlets.Measures; with Security.Openid.Servlets; with AWA.Users.Servlets; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Applications; with AWA.Workspaces.Modules; with AWA.Services.Filters; with AWA.Converters.Dates; with Atlas.Microblog.Modules; package Atlas.Applications is CONFIG_PATH : constant String := "/atlas"; CONTEXT_PATH : constant String := "/atlas"; ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas"; -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) function Get_Gravatar_Link (Email : in String) return String; -- EL function to convert an Email address to a Gravatar image. function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; -- Initialize the application. procedure Initialize (App : in Application_Access); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. overriding procedure Initialize_Components (App : in out Application); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. overriding procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. overriding procedure Initialize_Filters (App : in out Application); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. overriding procedure Initialize_Modules (App : in out Application); private type Application is new AWA.Applications.Application with record Self : Application_Access; -- Application servlets and filters (add new servlet and filter instances here). Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; -- Authentication servlet and filter. Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; -- Converters shared by web requests. Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; -- The application modules. User_Module : aliased AWA.Users.Modules.User_Module; Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module; Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; Mail_Module : aliased AWA.Mail.Modules.Mail_Module; Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module; -- XXX_Module : aliased Atlas.XXX.Module.XXX_Module; end record; end Atlas.Applications;
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Filters.Dump; with ASF.Servlets.Measures; with ASF.Security.Servlets; with AWA.Users.Servlets; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Applications; with AWA.Workspaces.Modules; with AWA.Services.Filters; with AWA.Converters.Dates; with Atlas.Microblog.Modules; package Atlas.Applications is CONFIG_PATH : constant String := "/atlas"; CONTEXT_PATH : constant String := "/atlas"; ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas"; -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) function Get_Gravatar_Link (Email : in String) return String; -- EL function to convert an Email address to a Gravatar image. function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; -- Initialize the application. procedure Initialize (App : in Application_Access); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. overriding procedure Initialize_Components (App : in out Application); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. overriding procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. overriding procedure Initialize_Filters (App : in out Application); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. overriding procedure Initialize_Modules (App : in out Application); private type Application is new AWA.Applications.Application with record Self : Application_Access; -- Application servlets and filters (add new servlet and filter instances here). Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; -- Authentication servlet and filter. Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; -- Converters shared by web requests. Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; -- The application modules. User_Module : aliased AWA.Users.Modules.User_Module; Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module; Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; Mail_Module : aliased AWA.Mail.Modules.Mail_Module; Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module; -- XXX_Module : aliased Atlas.XXX.Module.XXX_Module; end record; end Atlas.Applications;
Use ASF.Security.Servlets
Use ASF.Security.Servlets
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ead47d0870638d59e4c9903501188181e266b323
regtests/util-events-channels-tests.adb
regtests/util-events-channels-tests.adb
----------------------------------------------------------------------- -- events.tests -- Unit tests for event channels -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; package body Util.Events.Channels.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Events.Channels"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Channels.Post_Event", Test_Post_Event'Access); end Add_Tests; procedure Receive_Event (Sub : in out Test; Item : in Event'Class) is pragma Unreferenced (Item); begin Sub.Count := Sub.Count + 1; end Receive_Event; procedure Test_Post_Event (T : in out Test) is C : constant Channel_Access := Create ("test", "direct"); E : Event; T1 : aliased Test; T2 : aliased Test; begin C.Post (E); Assert_Equals (T, "test", C.Get_Name, "Invalid channel name"); C.Subscribe (T1'Unchecked_Access); C.Post (E); Assert_Equals (T, 1, T1.Count, "Invalid number of received events"); Assert_Equals (T, 0, T2.Count, "Invalid number of events"); C.Subscribe (T2'Unchecked_Access); C.Post (E); C.Unsubscribe (T1'Unchecked_Access); C.Post (E); Assert_Equals (T, 2, T1.Count, "Invalid number of received events"); Assert_Equals (T, 2, T2.Count, "Invalid number of events"); end Test_Post_Event; end Util.Events.Channels.Tests;
----------------------------------------------------------------------- -- events.tests -- Unit tests for event channels -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Test_Caller; package body Util.Events.Channels.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Events.Channels"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Channels.Post_Event", Test_Post_Event'Access); end Add_Tests; procedure Receive_Event (Sub : in out Test; Item : in Event'Class) is pragma Unreferenced (Item); begin Sub.Count := Sub.Count + 1; end Receive_Event; procedure Test_Post_Event (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => Channel'Class, Name => Channel_Access); C : Channel_Access := Create ("test", "direct"); E : Event; T1 : aliased Test; T2 : aliased Test; begin C.Post (E); Assert_Equals (T, "test", C.Get_Name, "Invalid channel name"); C.Subscribe (T1'Unchecked_Access); C.Post (E); Assert_Equals (T, 1, T1.Count, "Invalid number of received events"); Assert_Equals (T, 0, T2.Count, "Invalid number of events"); C.Subscribe (T2'Unchecked_Access); C.Post (E); C.Unsubscribe (T1'Unchecked_Access); C.Post (E); Assert_Equals (T, 2, T1.Count, "Invalid number of received events"); Assert_Equals (T, 2, T2.Count, "Invalid number of events"); Free (C); end Test_Post_Event; end Util.Events.Channels.Tests;
Fix memory leak in the unit test
Fix memory leak in the unit test
Ada
apache-2.0
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
763a80fd1700d83c3660aebb32f5e31e5ec7de22
src/gen-commands-templates.ads
src/gen-commands-templates.ads
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- Copyright (C) 2011, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Util.Strings.Sets; with Util.Strings.Vectors; package Gen.Commands.Templates is -- ------------------------------ -- Template Generic Command -- ------------------------------ -- This command adds a XHTML page to the web application. type Command is new Gen.Commands.Command with private; type Command_Access is access all Command'Class; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Read the template commands defined in dynamo configuration directory. procedure Read_Commands (Generator : in out Gen.Generator.Handler); private type Param is record Name : Ada.Strings.Unbounded.Unbounded_String; Argument : Ada.Strings.Unbounded.Unbounded_String; Value : Ada.Strings.Unbounded.Unbounded_String; Is_Optional : Boolean := False; end record; package Param_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Param); type Patch is record Template : Ada.Strings.Unbounded.Unbounded_String; After : Util.Strings.Vectors.Vector; Missing : Util.Strings.Vectors.Vector; Before : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; Optional : Boolean := False; end record; package Patch_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Patch); type Command is new Gen.Commands.Command with record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; Help_Msg : Ada.Strings.Unbounded.Unbounded_String; Base_Dir : Ada.Strings.Unbounded.Unbounded_String; Templates : Util.Strings.Sets.Set; Patches : Patch_Vectors.Vector; Params : Param_Vectors.Vector; end record; end Gen.Commands.Templates;
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- Copyright (C) 2011, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Util.Strings.Sets; with Util.Strings.Vectors; package Gen.Commands.Templates is -- ------------------------------ -- Template Generic Command -- ------------------------------ -- This command adds a XHTML page to the web application. type Command is new Gen.Commands.Command with private; type Command_Access is access all Command'Class; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Read the template commands defined in dynamo configuration directory. procedure Read_Commands (Generator : in out Gen.Generator.Handler); private type Param is record Name : Ada.Strings.Unbounded.Unbounded_String; Argument : Ada.Strings.Unbounded.Unbounded_String; Value : Ada.Strings.Unbounded.Unbounded_String; Is_Optional : Boolean := False; end record; package Param_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Param); type Patch is record Template : Ada.Strings.Unbounded.Unbounded_String; After : Util.Strings.Vectors.Vector; Missing : Util.Strings.Vectors.Vector; Before : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; Optional : Boolean := False; end record; package Patch_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Patch); type Command is new Gen.Commands.Command with record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; Help_Msg : Ada.Strings.Unbounded.Unbounded_String; Base_Dir : Ada.Strings.Unbounded.Unbounded_String; Templates : Util.Strings.Sets.Set; Patches : Patch_Vectors.Vector; Params : Param_Vectors.Vector; end record; end Gen.Commands.Templates;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo