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
|
---|---|---|---|---|---|---|---|---|---|
5404e97c422e13f54195242bc158e7ab8b8a749e
|
src/gl/implementation/gl-objects-framebuffers.adb
|
src/gl/implementation/gl-objects-framebuffers.adb
|
-- Copyright (c) 2013 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 Ada.Containers.Indefinite_Holders;
with Ada.Unchecked_Conversion;
with GL.API;
with GL.Enums.Getter;
with GL.Pixels.Queries;
package body GL.Objects.Framebuffers is
function Valid_Attachment
(Attachment : Attachment_Point;
Texture : Textures.Texture) return Boolean
is
use all type GL.Pixels.Internal_Format;
Format : GL.Pixels.Internal_Format renames Texture.Internal_Format (Level => 0);
begin
case Attachment is
when Depth_Stencil_Attachment =>
return Format in Depth24_Stencil8 | Depth32F_Stencil8;
when Depth_Attachment =>
return Format in Depth_Component16 | Depth_Component24 | Depth_Component32F;
when Stencil_Attachment =>
return Format in Stencil_Index8;
when others =>
return GL.Pixels.Queries.Color_Renderable (Format, Texture.Kind);
end case;
end Valid_Attachment;
function Status
(Object : Framebuffer;
Target : Framebuffer_Target'Class) return Framebuffer_Status is
begin
return API.Check_Named_Framebuffer_Status (Object.Reference.GL_Id, Target.Kind);
end Status;
procedure Set_Draw_Buffer
(Object : Framebuffer;
Selector : Buffers.Color_Buffer_Selector) is
begin
Object.Set_Draw_Buffers ((1 => Selector));
end Set_Draw_Buffer;
procedure Set_Draw_Buffers
(Object : Framebuffer;
List : Buffers.Color_Buffer_List) is
begin
API.Named_Framebuffer_Draw_Buffers (Object.Reference.GL_Id, List'Length, List);
Raise_Exception_On_OpenGL_Error;
end Set_Draw_Buffers;
procedure Set_Read_Buffer (Object : Framebuffer; Selector : Buffers.Color_Buffer_Selector) is
begin
API.Named_Framebuffer_Read_Buffer (Object.Reference.GL_Id, Selector);
Raise_Exception_On_OpenGL_Error;
end Set_Read_Buffer;
procedure Attach_Texture (Object : Framebuffer;
Attachment : Attachment_Point;
Texture_Object : Textures.Texture;
Level : Textures.Mipmap_Level) is
begin
API.Named_Framebuffer_Texture (Object.Reference.GL_Id, Attachment,
Texture_Object.Raw_Id, Level);
Raise_Exception_On_OpenGL_Error;
end Attach_Texture;
procedure Attach_Texture_Layer (Object : Framebuffer;
Attachment : Attachment_Point;
Texture_Object : Textures.Texture;
Level : Textures.Mipmap_Level;
Layer : Natural) is
begin
API.Named_Framebuffer_Texture_Layer (Object.Reference.GL_Id, Attachment,
Texture_Object.Raw_Id, Level, Int (Layer));
Raise_Exception_On_OpenGL_Error;
end Attach_Texture_Layer;
procedure Detach (Object : Framebuffer; Attachment : Attachment_Point) is
begin
API.Named_Framebuffer_Texture (Object.Reference.GL_Id, Attachment, 0, 0);
Raise_Exception_On_OpenGL_Error;
end Detach;
procedure Invalidate_Data (Object : Framebuffer;
Attachments : Attachment_List) is
begin
API.Invalidate_Named_Framebuffer_Data
(Object.Reference.GL_Id, Attachments'Length, Attachments);
Raise_Exception_On_OpenGL_Error;
end Invalidate_Data;
procedure Invalidate_Sub_Data (Object : Framebuffer;
Attachments : Attachment_List;
X, Y : Int;
Width, Height : Size) is
begin
API.Invalidate_Named_Framebuffer_Sub_Data (Object.Reference.GL_Id, Attachments'Length,
Attachments, X, Y, Width, Height);
Raise_Exception_On_OpenGL_Error;
end Invalidate_Sub_Data;
procedure Blit (Read_Object, Draw_Object : Framebuffer;
Src_X0, Src_Y0, Src_X1, Src_Y1,
Dst_X0, Dst_Y0, Dst_X1, Dst_Y1 : Int;
Mask : Buffers.Buffer_Bits;
Filter : Textures.Magnifying_Function)
is
use type Low_Level.Bitfield;
function Convert is new Ada.Unchecked_Conversion
(Buffers.Buffer_Bits, Low_Level.Bitfield);
Raw_Bits : constant Low_Level.Bitfield
:= Convert (Mask) and 2#0100010100000000#;
begin
API.Blit_Named_Framebuffer (Read_Object.Reference.GL_Id,
Draw_Object.Reference.GL_Id,
Src_X0, Src_Y0, Src_X1, Src_Y1,
Dst_X0, Dst_Y0, Dst_X1, Dst_Y1,
Raw_Bits, Filter);
Raise_Exception_On_OpenGL_Error;
end Blit;
procedure Set_Default_Width (Object : Framebuffer; Value : Size) is
begin
API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id,
Enums.Default_Width, Value);
Raise_Exception_On_OpenGL_Error;
end Set_Default_Width;
function Default_Width (Object : Framebuffer) return Size is
Ret : aliased Size;
begin
API.Get_Named_Framebuffer_Parameter_Size
(Object.Reference.GL_Id, Enums.Default_Width, Ret'Unchecked_Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Default_Width;
function Max_Framebuffer_Width return Size is
Ret : Size := 16_384;
begin
API.Get_Size (Enums.Getter.Max_Framebuffer_Width, Ret);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Max_Framebuffer_Width;
procedure Set_Default_Height (Object : Framebuffer; Value : Size) is
begin
API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id,
Enums.Default_Height,
Value);
Raise_Exception_On_OpenGL_Error;
end Set_Default_Height;
function Default_Height (Object : Framebuffer) return Size is
Ret : aliased Size;
begin
API.Get_Named_Framebuffer_Parameter_Size
(Object.Reference.GL_Id, Enums.Default_Height, Ret'Unchecked_Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Default_Height;
function Max_Framebuffer_Height return Size is
Ret : Size := 16_384;
begin
API.Get_Size (Enums.Getter.Max_Framebuffer_Height, Ret);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Max_Framebuffer_Height;
procedure Set_Default_Layers (Object : Framebuffer; Value : Size) is
begin
API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id,
Enums.Default_Layers, Value);
Raise_Exception_On_OpenGL_Error;
end Set_Default_Layers;
function Default_Layers (Object : Framebuffer) return Size is
Ret : aliased Size;
begin
API.Get_Named_Framebuffer_Parameter_Size
(Object.Reference.GL_Id, Enums.Default_Layers, Ret'Unchecked_Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Default_Layers;
function Max_Framebuffer_Layers return Size is
Ret : Size := 2_048;
begin
API.Get_Size (Enums.Getter.Max_Framebuffer_Layers, Ret);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Max_Framebuffer_Layers;
procedure Set_Default_Samples (Object : Framebuffer; Value : Size) is
begin
API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id,
Enums.Default_Samples,
Value);
Raise_Exception_On_OpenGL_Error;
end Set_Default_Samples;
function Default_Samples (Object : Framebuffer) return Size is
Ret : aliased Size;
begin
API.Get_Named_Framebuffer_Parameter_Size
(Object.Reference.GL_Id, Enums.Default_Samples, Ret'Unchecked_Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Default_Samples;
function Max_Framebuffer_Samples return Size is
Ret : Size := 4;
begin
API.Get_Size (Enums.Getter.Max_Framebuffer_Samples, Ret);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Max_Framebuffer_Samples;
procedure Set_Default_Fixed_Sample_Locations (Object : Framebuffer; Value : Boolean) is
begin
API.Named_Framebuffer_Parameter_Bool (Object.Reference.GL_Id,
Enums.Default_Fixed_Sample_Locations,
Low_Level.Bool (Value));
Raise_Exception_On_OpenGL_Error;
end Set_Default_Fixed_Sample_Locations;
function Default_Fixed_Sample_Locations (Object : Framebuffer) return Boolean is
Ret : aliased Low_Level.Bool;
begin
API.Get_Named_Framebuffer_Parameter_Bool
(Object.Reference.GL_Id, Enums.Default_Fixed_Sample_Locations,
Ret'Unchecked_Access);
Raise_Exception_On_OpenGL_Error;
return Boolean (Ret);
end Default_Fixed_Sample_Locations;
overriding
procedure Initialize_Id (Object : in out Framebuffer) is
New_Id : UInt := 0;
begin
API.Create_Framebuffers (1, New_Id);
Raise_Exception_On_OpenGL_Error;
Object.Reference.GL_Id := New_Id;
Object.Reference.Initialized := True;
end Initialize_Id;
overriding
procedure Delete_Id (Object : in out Framebuffer) is
Arr : constant Low_Level.UInt_Array := (1 => Object.Reference.GL_Id);
begin
API.Delete_Framebuffers (1, Arr);
Raise_Exception_On_OpenGL_Error;
Object.Reference.GL_Id := 0;
Object.Reference.Initialized := False;
end Delete_Id;
package Framebuffer_Holder is new Ada.Containers.Indefinite_Holders
(Element_Type => Framebuffer'Class);
type Framebuffer_Target_Array is
array (Enums.Framebuffer_Kind) of Framebuffer_Holder.Holder;
Current_Framebuffers : Framebuffer_Target_Array;
procedure Bind (Target : Framebuffer_Target;
Object : Framebuffer'Class) is
Holder : Framebuffer_Holder.Holder := Current_Framebuffers (Target.Kind);
begin
if Holder.Is_Empty or else Object /= Holder.Element then
API.Bind_Framebuffer (Target.Kind, Object.Reference.GL_Id);
Raise_Exception_On_OpenGL_Error;
Holder.Replace_Element (Object);
end if;
end Bind;
function Current (Target : Framebuffer_Target) return Framebuffer'Class is
Holder : constant Framebuffer_Holder.Holder := Current_Framebuffers (Target.Kind);
begin
if Holder.Is_Empty then
raise No_Object_Bound_Exception with Target.Kind'Image;
else
return Holder.Element;
end if;
end Current;
procedure Clear_Color_Buffer (Object : Framebuffer;
Index : Buffers.Draw_Buffer_Index;
Value : Colors.Color) is
begin
API.Clear_Named_Framebuffer_Color_Real
(Object.Reference.GL_Id, Enums.Color_Buffer, Index, Value);
-- TODO Use *fv to clear fixed- and floating-point, *iv for signed int, *uiv for unsigned
Raise_Exception_On_OpenGL_Error;
end Clear_Color_Buffer;
procedure Clear_Depth_Buffer (Object : Framebuffer; Value : Buffers.Depth) is
Aliased_Value : aliased Buffers.Depth := Value;
begin
API.Clear_Named_Framebuffer_Depth
(Object.Reference.GL_Id, Enums.Depth_Buffer, 0, Aliased_Value);
Raise_Exception_On_OpenGL_Error;
end Clear_Depth_Buffer;
procedure Clear_Stencil_Buffer (Object : Framebuffer; Value : Buffers.Stencil_Index) is
Aliased_Value : aliased Buffers.Stencil_Index := Value;
begin
API.Clear_Named_Framebuffer_Stencil
(Object.Reference.GL_Id, Enums.Stencil_Buffer, 0, Aliased_Value);
Raise_Exception_On_OpenGL_Error;
end Clear_Stencil_Buffer;
procedure Clear_Depth_And_Stencil_Buffer (Object : Framebuffer;
Depth_Value : Buffers.Depth;
Stencil_Value : Buffers.Stencil_Index) is
begin
API.Clear_Named_Framebuffer_Depth_Stencil
(Object.Reference.GL_Id, Enums.Depth_Stencil_Buffer, 0, Depth_Value, Stencil_Value);
Raise_Exception_On_OpenGL_Error;
end Clear_Depth_And_Stencil_Buffer;
-----------------------------------------------------------------------------
type Default_Framebuffer_Type is new Framebuffer with null record;
overriding
procedure Initialize_Id (Object : in out Default_Framebuffer_Type) is null;
overriding
procedure Delete_Id (Object : in out Default_Framebuffer_Type) is null;
Default_FB : constant Default_Framebuffer_Type
:= Default_Framebuffer_Type'(GL_Object with null record);
function Default_Framebuffer return Framebuffer is (Framebuffer (Default_FB));
end GL.Objects.Framebuffers;
|
-- Copyright (c) 2013 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 Ada.Containers.Indefinite_Holders;
with Ada.Unchecked_Conversion;
with GL.API;
with GL.Enums.Getter;
with GL.Pixels.Queries;
package body GL.Objects.Framebuffers is
function Valid_Attachment
(Attachment : Attachment_Point;
Texture : Textures.Texture) return Boolean
is
use all type GL.Pixels.Internal_Format;
Format : GL.Pixels.Internal_Format renames Texture.Internal_Format (Level => 0);
begin
case Attachment is
when Depth_Stencil_Attachment =>
return Format in Depth24_Stencil8 | Depth32F_Stencil8;
when Depth_Attachment =>
return Format in Depth_Component16 | Depth_Component24 | Depth_Component32F;
when Stencil_Attachment =>
return Format in Stencil_Index8;
when others =>
return GL.Pixels.Queries.Color_Renderable (Format, Texture.Kind);
end case;
end Valid_Attachment;
function Status
(Object : Framebuffer;
Target : Framebuffer_Target'Class) return Framebuffer_Status is
begin
return API.Check_Named_Framebuffer_Status (Object.Reference.GL_Id, Target.Kind);
end Status;
procedure Set_Draw_Buffer
(Object : Framebuffer;
Selector : Buffers.Color_Buffer_Selector)
is
subtype Index_Type is Buffers.Draw_Buffer_Index;
begin
Object.Set_Draw_Buffers
((Index_Type'First => Selector,
Index_Type'First + 1 .. Index_Type'Last => Buffers.None));
end Set_Draw_Buffer;
procedure Set_Draw_Buffers
(Object : Framebuffer;
List : Buffers.Color_Buffer_List) is
begin
API.Named_Framebuffer_Draw_Buffers (Object.Reference.GL_Id, List'Length, List);
Raise_Exception_On_OpenGL_Error;
end Set_Draw_Buffers;
procedure Set_Read_Buffer (Object : Framebuffer; Selector : Buffers.Color_Buffer_Selector) is
begin
API.Named_Framebuffer_Read_Buffer (Object.Reference.GL_Id, Selector);
Raise_Exception_On_OpenGL_Error;
end Set_Read_Buffer;
procedure Attach_Texture (Object : Framebuffer;
Attachment : Attachment_Point;
Texture_Object : Textures.Texture;
Level : Textures.Mipmap_Level) is
begin
API.Named_Framebuffer_Texture (Object.Reference.GL_Id, Attachment,
Texture_Object.Raw_Id, Level);
Raise_Exception_On_OpenGL_Error;
end Attach_Texture;
procedure Attach_Texture_Layer (Object : Framebuffer;
Attachment : Attachment_Point;
Texture_Object : Textures.Texture;
Level : Textures.Mipmap_Level;
Layer : Natural) is
begin
API.Named_Framebuffer_Texture_Layer (Object.Reference.GL_Id, Attachment,
Texture_Object.Raw_Id, Level, Int (Layer));
Raise_Exception_On_OpenGL_Error;
end Attach_Texture_Layer;
procedure Detach (Object : Framebuffer; Attachment : Attachment_Point) is
begin
API.Named_Framebuffer_Texture (Object.Reference.GL_Id, Attachment, 0, 0);
Raise_Exception_On_OpenGL_Error;
end Detach;
procedure Invalidate_Data (Object : Framebuffer;
Attachments : Attachment_List) is
begin
API.Invalidate_Named_Framebuffer_Data
(Object.Reference.GL_Id, Attachments'Length, Attachments);
Raise_Exception_On_OpenGL_Error;
end Invalidate_Data;
procedure Invalidate_Sub_Data (Object : Framebuffer;
Attachments : Attachment_List;
X, Y : Int;
Width, Height : Size) is
begin
API.Invalidate_Named_Framebuffer_Sub_Data (Object.Reference.GL_Id, Attachments'Length,
Attachments, X, Y, Width, Height);
Raise_Exception_On_OpenGL_Error;
end Invalidate_Sub_Data;
procedure Blit (Read_Object, Draw_Object : Framebuffer;
Src_X0, Src_Y0, Src_X1, Src_Y1,
Dst_X0, Dst_Y0, Dst_X1, Dst_Y1 : Int;
Mask : Buffers.Buffer_Bits;
Filter : Textures.Magnifying_Function)
is
use type Low_Level.Bitfield;
function Convert is new Ada.Unchecked_Conversion
(Buffers.Buffer_Bits, Low_Level.Bitfield);
Raw_Bits : constant Low_Level.Bitfield
:= Convert (Mask) and 2#0100010100000000#;
begin
API.Blit_Named_Framebuffer (Read_Object.Reference.GL_Id,
Draw_Object.Reference.GL_Id,
Src_X0, Src_Y0, Src_X1, Src_Y1,
Dst_X0, Dst_Y0, Dst_X1, Dst_Y1,
Raw_Bits, Filter);
Raise_Exception_On_OpenGL_Error;
end Blit;
procedure Set_Default_Width (Object : Framebuffer; Value : Size) is
begin
API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id,
Enums.Default_Width, Value);
Raise_Exception_On_OpenGL_Error;
end Set_Default_Width;
function Default_Width (Object : Framebuffer) return Size is
Ret : aliased Size;
begin
API.Get_Named_Framebuffer_Parameter_Size
(Object.Reference.GL_Id, Enums.Default_Width, Ret'Unchecked_Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Default_Width;
function Max_Framebuffer_Width return Size is
Ret : Size := 16_384;
begin
API.Get_Size (Enums.Getter.Max_Framebuffer_Width, Ret);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Max_Framebuffer_Width;
procedure Set_Default_Height (Object : Framebuffer; Value : Size) is
begin
API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id,
Enums.Default_Height,
Value);
Raise_Exception_On_OpenGL_Error;
end Set_Default_Height;
function Default_Height (Object : Framebuffer) return Size is
Ret : aliased Size;
begin
API.Get_Named_Framebuffer_Parameter_Size
(Object.Reference.GL_Id, Enums.Default_Height, Ret'Unchecked_Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Default_Height;
function Max_Framebuffer_Height return Size is
Ret : Size := 16_384;
begin
API.Get_Size (Enums.Getter.Max_Framebuffer_Height, Ret);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Max_Framebuffer_Height;
procedure Set_Default_Layers (Object : Framebuffer; Value : Size) is
begin
API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id,
Enums.Default_Layers, Value);
Raise_Exception_On_OpenGL_Error;
end Set_Default_Layers;
function Default_Layers (Object : Framebuffer) return Size is
Ret : aliased Size;
begin
API.Get_Named_Framebuffer_Parameter_Size
(Object.Reference.GL_Id, Enums.Default_Layers, Ret'Unchecked_Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Default_Layers;
function Max_Framebuffer_Layers return Size is
Ret : Size := 2_048;
begin
API.Get_Size (Enums.Getter.Max_Framebuffer_Layers, Ret);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Max_Framebuffer_Layers;
procedure Set_Default_Samples (Object : Framebuffer; Value : Size) is
begin
API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id,
Enums.Default_Samples,
Value);
Raise_Exception_On_OpenGL_Error;
end Set_Default_Samples;
function Default_Samples (Object : Framebuffer) return Size is
Ret : aliased Size;
begin
API.Get_Named_Framebuffer_Parameter_Size
(Object.Reference.GL_Id, Enums.Default_Samples, Ret'Unchecked_Access);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Default_Samples;
function Max_Framebuffer_Samples return Size is
Ret : Size := 4;
begin
API.Get_Size (Enums.Getter.Max_Framebuffer_Samples, Ret);
Raise_Exception_On_OpenGL_Error;
return Ret;
end Max_Framebuffer_Samples;
procedure Set_Default_Fixed_Sample_Locations (Object : Framebuffer; Value : Boolean) is
begin
API.Named_Framebuffer_Parameter_Bool (Object.Reference.GL_Id,
Enums.Default_Fixed_Sample_Locations,
Low_Level.Bool (Value));
Raise_Exception_On_OpenGL_Error;
end Set_Default_Fixed_Sample_Locations;
function Default_Fixed_Sample_Locations (Object : Framebuffer) return Boolean is
Ret : aliased Low_Level.Bool;
begin
API.Get_Named_Framebuffer_Parameter_Bool
(Object.Reference.GL_Id, Enums.Default_Fixed_Sample_Locations,
Ret'Unchecked_Access);
Raise_Exception_On_OpenGL_Error;
return Boolean (Ret);
end Default_Fixed_Sample_Locations;
overriding
procedure Initialize_Id (Object : in out Framebuffer) is
New_Id : UInt := 0;
begin
API.Create_Framebuffers (1, New_Id);
Raise_Exception_On_OpenGL_Error;
Object.Reference.GL_Id := New_Id;
Object.Reference.Initialized := True;
end Initialize_Id;
overriding
procedure Delete_Id (Object : in out Framebuffer) is
Arr : constant Low_Level.UInt_Array := (1 => Object.Reference.GL_Id);
begin
API.Delete_Framebuffers (1, Arr);
Raise_Exception_On_OpenGL_Error;
Object.Reference.GL_Id := 0;
Object.Reference.Initialized := False;
end Delete_Id;
package Framebuffer_Holder is new Ada.Containers.Indefinite_Holders
(Element_Type => Framebuffer'Class);
type Framebuffer_Target_Array is
array (Enums.Framebuffer_Kind) of Framebuffer_Holder.Holder;
Current_Framebuffers : Framebuffer_Target_Array;
procedure Bind (Target : Framebuffer_Target;
Object : Framebuffer'Class) is
Holder : Framebuffer_Holder.Holder := Current_Framebuffers (Target.Kind);
begin
if Holder.Is_Empty or else Object /= Holder.Element then
API.Bind_Framebuffer (Target.Kind, Object.Reference.GL_Id);
Raise_Exception_On_OpenGL_Error;
Holder.Replace_Element (Object);
end if;
end Bind;
function Current (Target : Framebuffer_Target) return Framebuffer'Class is
Holder : constant Framebuffer_Holder.Holder := Current_Framebuffers (Target.Kind);
begin
if Holder.Is_Empty then
raise No_Object_Bound_Exception with Target.Kind'Image;
else
return Holder.Element;
end if;
end Current;
procedure Clear_Color_Buffer (Object : Framebuffer;
Index : Buffers.Draw_Buffer_Index;
Value : Colors.Color) is
begin
API.Clear_Named_Framebuffer_Color_Real
(Object.Reference.GL_Id, Enums.Color_Buffer, Index, Value);
-- TODO Use *fv to clear fixed- and floating-point, *iv for signed int, *uiv for unsigned
Raise_Exception_On_OpenGL_Error;
end Clear_Color_Buffer;
procedure Clear_Depth_Buffer (Object : Framebuffer; Value : Buffers.Depth) is
Aliased_Value : aliased Buffers.Depth := Value;
begin
API.Clear_Named_Framebuffer_Depth
(Object.Reference.GL_Id, Enums.Depth_Buffer, 0, Aliased_Value);
Raise_Exception_On_OpenGL_Error;
end Clear_Depth_Buffer;
procedure Clear_Stencil_Buffer (Object : Framebuffer; Value : Buffers.Stencil_Index) is
Aliased_Value : aliased Buffers.Stencil_Index := Value;
begin
API.Clear_Named_Framebuffer_Stencil
(Object.Reference.GL_Id, Enums.Stencil_Buffer, 0, Aliased_Value);
Raise_Exception_On_OpenGL_Error;
end Clear_Stencil_Buffer;
procedure Clear_Depth_And_Stencil_Buffer (Object : Framebuffer;
Depth_Value : Buffers.Depth;
Stencil_Value : Buffers.Stencil_Index) is
begin
API.Clear_Named_Framebuffer_Depth_Stencil
(Object.Reference.GL_Id, Enums.Depth_Stencil_Buffer, 0, Depth_Value, Stencil_Value);
Raise_Exception_On_OpenGL_Error;
end Clear_Depth_And_Stencil_Buffer;
-----------------------------------------------------------------------------
type Default_Framebuffer_Type is new Framebuffer with null record;
overriding
procedure Initialize_Id (Object : in out Default_Framebuffer_Type) is null;
overriding
procedure Delete_Id (Object : in out Default_Framebuffer_Type) is null;
Default_FB : constant Default_Framebuffer_Type
:= Default_Framebuffer_Type'(GL_Object with null record);
function Default_Framebuffer return Framebuffer is (Framebuffer (Default_FB));
end GL.Objects.Framebuffers;
|
Fix procedure Set_Draw_Buffer in package GL.Objects.Framebuffers
|
gl: Fix procedure Set_Draw_Buffer in package GL.Objects.Framebuffers
The first index must be set to the given selector and all other indices
to None.
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
38934feb0355be083888119e33344c78d0326558
|
regtests/util-http-clients-tests.adb
|
regtests/util-http-clients-tests.adb
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Http.Tools;
with Util.Strings;
with Util.Log.Loggers;
package body Util.Http.Clients.Tests is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests");
package body Http_Tests is
package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get",
Test_Http_Get'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post",
Test_Http_Post'Access);
end Add_Tests;
overriding
procedure Set_Up (T : in out Http_Test) is
begin
Test (T).Set_Up;
Register;
end Set_Up;
end Http_Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
Log.Info ("Starting test server");
T.Server := new Test_Server;
T.Server.Start;
end Set_Up;
overriding
procedure Tear_Down (T : in out Test) is
begin
if T.Server /= null then
Log.Info ("Stopping test server");
T.Server.Stop;
T.Server := null;
end if;
end Tear_Down;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
L : constant String := Ada.Strings.Unbounded.To_String (Line);
Pos : Natural := Util.Strings.Index (L, ' ');
begin
if Pos > 0 and Into.Method = UNKNOWN then
if L (L'First .. Pos - 1) = "GET" then
Into.Method := GET;
elsif L (L'First .. Pos - 1) = "POST" then
Into.Method := POST;
else
Into.Method := UNKNOWN;
end if;
end if;
Pos := Util.Strings.Index (L, ':');
if Pos > 0 then
if L (L'First .. Pos) = "Content-Type:" then
Into.Content_Type
:= Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2));
elsif L (L'First .. Pos) = "Content-Length:" then
Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2));
end if;
end if;
if L'Length = 2 and then Into.Length > 0 then
for I in 1 .. Into.Length loop
declare
C : Character;
begin
Stream.Read (C);
Ada.Strings.Unbounded.Append (Into.Result, C);
end;
end loop;
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF);
Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Write ("OK" & ASCII.CR & ASCII.LF);
Output.Flush;
end;
end if;
Log.Info ("Received: {0}", L);
end Process_Line;
-- ------------------------------
-- Get the test server base URI.
-- ------------------------------
function Get_Uri (T : in Test) return String is
begin
return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port);
end Get_Uri;
-- ------------------------------
-- Test the http Get operation.
-- ------------------------------
procedure Test_Http_Get (T : in out Test) is
Request : Client;
Reply : Response;
begin
Request.Get ("http://www.google.com", Reply);
T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True);
-- Check the content.
declare
Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body);
begin
Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content");
end;
-- Check one header.
declare
Content : constant String := Reply.Get_Header ("Content-Type");
begin
T.Assert (Content'Length > 0, "Empty Content-Type header");
Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type");
end;
end Test_Http_Get;
-- ------------------------------
-- Test the http POST operation.
-- ------------------------------
procedure Test_Http_Post (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Post on " & Uri);
T.Server.Method := UNKNOWN;
Request.Post (Uri & "/post",
"p1=1", Reply);
T.Assert (T.Server.Method = POST, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True);
end Test_Http_Post;
end Util.Http.Clients.Tests;
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Http.Tools;
with Util.Strings;
with Util.Log.Loggers;
package body Util.Http.Clients.Tests is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests");
package body Http_Tests is
package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get",
Test_Http_Get'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post",
Test_Http_Post'Access);
end Add_Tests;
overriding
procedure Set_Up (T : in out Http_Test) is
begin
Test (T).Set_Up;
Register;
end Set_Up;
end Http_Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
Log.Info ("Starting test server");
T.Server := new Test_Server;
T.Server.Start;
end Set_Up;
overriding
procedure Tear_Down (T : in out Test) is
begin
if T.Server /= null then
Log.Info ("Stopping test server");
T.Server.Stop;
T.Server := null;
end if;
end Tear_Down;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
L : constant String := Ada.Strings.Unbounded.To_String (Line);
Pos : Natural := Util.Strings.Index (L, ' ');
begin
if Pos > 0 and Into.Method = UNKNOWN then
if L (L'First .. Pos - 1) = "GET" then
Into.Method := GET;
elsif L (L'First .. Pos - 1) = "POST" then
Into.Method := POST;
else
Into.Method := UNKNOWN;
end if;
end if;
Pos := Util.Strings.Index (L, ':');
if Pos > 0 then
if L (L'First .. Pos) = "Content-Type:" then
Into.Content_Type
:= Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2));
elsif L (L'First .. Pos) = "Content-Length:" then
Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2));
end if;
end if;
if L'Length = 2 and then Into.Length > 0 then
for I in 1 .. Into.Length loop
declare
C : Character;
begin
Stream.Read (C);
Ada.Strings.Unbounded.Append (Into.Result, C);
end;
end loop;
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF);
Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Write ("OK" & ASCII.CR & ASCII.LF);
Output.Flush;
end;
end if;
Log.Info ("Received: {0}", L);
end Process_Line;
-- ------------------------------
-- Get the test server base URI.
-- ------------------------------
function Get_Uri (T : in Test) return String is
begin
return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port);
end Get_Uri;
-- ------------------------------
-- Test the http Get operation.
-- ------------------------------
procedure Test_Http_Get (T : in out Test) is
Request : Client;
Reply : Response;
begin
Request.Get ("http://www.google.com", Reply);
T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True);
-- Check the content.
declare
Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body);
begin
Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content");
end;
-- Check one header.
declare
Content : constant String := Reply.Get_Header ("Content-Type");
begin
T.Assert (Content'Length > 0, "Empty Content-Type header");
Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type");
end;
end Test_Http_Get;
-- ------------------------------
-- Test the http POST operation.
-- ------------------------------
procedure Test_Http_Post (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Post on " & Uri);
T.Server.Method := UNKNOWN;
Request.Post (Uri & "/post",
"p1=1", Reply);
T.Assert (T.Server.Method = POST, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True);
end Test_Http_Post;
end Util.Http.Clients.Tests;
|
Fix the implementation of the post server unit test
|
Fix the implementation of the post server unit test
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
|
9caf0c4f5fe632417d8339365c6fce23caadfbfa
|
src/tests/aunit/util-xunit.ads
|
src/tests/aunit/util-xunit.ads
|
-----------------------------------------------------------------------
-- util-xunit - Unit tests on top of AUnit
-- 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 AUnit;
with AUnit.Simple_Test_Cases;
with AUnit.Test_Suites;
with AUnit.Test_Fixtures;
with Ada.Strings.Unbounded;
with GNAT.Source_Info;
-- The <b>Util.XUnit</b> package exposes a common package definition used by the Ada testutil
-- library. It is intended to hide the details of the AUnit implementation.
-- A quite identical package exist for Ahven implementation.
package Util.XUnit is
use Ada.Strings.Unbounded;
use AUnit.Test_Suites;
subtype Status is AUnit.Status;
Success : constant Status := AUnit.Success;
Failure : constant Status := AUnit.Failure;
subtype Message_String is AUnit.Message_String;
subtype Test_Suite is AUnit.Test_Suites.Test_Suite;
subtype Access_Test_Suite is AUnit.Test_Suites.Access_Test_Suite;
function Format (S : in String) return Message_String renames AUnit.Format;
type Test_Case is abstract new AUnit.Simple_Test_Cases.Test_Case with null record;
-- 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);
type Test is abstract new AUnit.Test_Fixtures.Test_Fixture with null record;
-- maybe_overriding
procedure Assert (T : in Test;
Condition : in Boolean;
Message : in String := "Test failed";
Source : in String := GNAT.Source_Info.File;
Line : in Natural := GNAT.Source_Info.Line);
-- The main testsuite program. This launches the tests, collects the
-- results, create performance logs and set the program exit status
-- according to the testsuite execution status.
generic
with function Suite return Access_Test_Suite;
procedure Harness (Output : in Ada.Strings.Unbounded.Unbounded_String;
XML : in Boolean;
Result : out Status);
end Util.XUnit;
|
-----------------------------------------------------------------------
-- util-xunit - Unit tests on top of AUnit
-- Copyright (C) 2009, 2010, 2011, 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 AUnit;
with AUnit.Simple_Test_Cases;
with AUnit.Test_Suites;
with AUnit.Test_Fixtures;
with Ada.Strings.Unbounded;
with GNAT.Source_Info;
-- The <b>Util.XUnit</b> package exposes a common package definition used by the Ada testutil
-- library. It is intended to hide the details of the AUnit implementation.
-- A quite identical package exist for Ahven implementation.
package Util.XUnit is
use Ada.Strings.Unbounded;
use AUnit.Test_Suites;
subtype Status is AUnit.Status;
Success : constant Status := AUnit.Success;
Failure : constant Status := AUnit.Failure;
subtype Message_String is AUnit.Message_String;
subtype Test_Suite is AUnit.Test_Suites.Test_Suite;
subtype Access_Test_Suite is AUnit.Test_Suites.Access_Test_Suite;
function Format (S : in String) return Message_String renames AUnit.Format;
type Test_Case is abstract new AUnit.Simple_Test_Cases.Test_Case with null record;
-- 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);
type Test is abstract new AUnit.Test_Fixtures.Test_Fixture with null record;
-- maybe_overriding
procedure Assert (T : in Test;
Condition : in Boolean;
Message : in String := "Test failed";
Source : in String := GNAT.Source_Info.File;
Line : in Natural := GNAT.Source_Info.Line);
-- The main testsuite program. This launches the tests, collects the
-- results, create performance logs and set the program exit status
-- according to the testsuite execution status.
generic
with function Suite return Access_Test_Suite;
procedure Harness (Output : in String;
XML : in Boolean;
Label : in String;
Result : out Status);
end Util.XUnit;
|
Add Label parameter to Harness procedure
|
Add Label parameter to Harness procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
18cd96fb5cb8d6d327628ddb031850668a84ef27
|
samples/upload_servlet.adb
|
samples/upload_servlet.adb
|
-----------------------------------------------------------------------
-- upload_servlet -- Servlet example to upload files on the server
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Util.Streams.Pipes;
with Util.Strings;
with ASF.Parts;
package body Upload_Servlet is
-- ------------------------------
-- Write the upload form page with an optional response message.
-- ------------------------------
procedure Write (Response : in out Responses.Response'Class;
Message : in String) is
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Output.Write ("<html><head><title>Upload servlet example</title></head>"
& "<style></style>"
& "<body>"
& "<h1>Upload files to identify them</h1>");
-- Display the response or some error.
if Message /= "" then
Output.Write ("<h2>" & Message & "</h2>");
end if;
-- Render the form. If we have some existing Radius or Height
-- use them to set the initial values.
Output.Write ("<p>Identifies images, PDF, tar, tar.gz, zip</p>"
& "<form method='post' enctype='multipart/form-data'>"
& "<table>"
& "<tr><td>File 1</td>"
& "<td><input type='file' size='50' name='file1' maxlength='100000'/></td>"
& "</tr><tr><td>File 2</td>"
& "<td><input type='file' size='50' name='file2' maxlength='100000'/></td>"
& "</tr><tr><td>File 3</td>"
& "<td><input type='file' size='50' name='file3' maxlength='100000'/></td>"
& "</tr>"
& "<tr><td></td><td><input type='submit' value='Identify'></input></td></tr>"
& "</table></form>"
& "</body></html>");
Response.Set_Status (Responses.SC_OK);
end Write;
-- ------------------------------
-- Called by the servlet container when a GET request is received.
-- Display the volume form page.
-- ------------------------------
procedure Do_Get (Server : in Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server, Request);
begin
Write (Response, "");
end Do_Get;
-- ------------------------------
-- Execute a command and write the result to the output stream.
-- ------------------------------
procedure Execute (Command : in String;
Output : in out ASF.Streams.Print_Stream) is
use type Ada.Streams.Stream_Element_Offset;
Proc : Util.Streams.Pipes.Pipe_Stream;
Content : Ada.Streams.Stream_Element_Array (0 .. 1024);
Pos : Ada.Streams.Stream_Element_Offset;
begin
Proc.Open (Command);
loop
Proc.Read (Into => Content,
Last => Pos);
exit when Pos < 0;
Output.Write (Content (0 .. Pos));
end loop;
Proc.Close;
if Proc.Get_Exit_Status /= 0 then
Output.Write ("Command '" & Command & "' exited with code "
& Integer'Image (Proc.Get_Exit_Status));
end if;
end Execute;
-- ------------------------------
-- Guess a file type depending on a content type or a file name.
-- ------------------------------
function Get_File_Type (Content_Type : in String;
Name : in String) return File_Type is
begin
if Content_Type = "application/pdf" then
return PDF;
elsif Content_Type = "image/png" or Content_Type = "image/jpeg" then
return IMAGE;
elsif Content_Type = "image/gif" then
return IMAGE;
elsif Content_Type = "application/zip" then
return ZIP;
end if;
declare
Ext_Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Ext_Pos > 0 then
if Name (Ext_Pos .. Name'Last) = ".gz" or Name (Ext_Pos .. Name'Last) = ".tgz" then
return TAR_GZ;
elsif Name (Ext_Pos .. Name'Last) = ".tar" then
return TAR;
elsif Name (Ext_Pos .. Name'Last) = ".jpg"
or Name (Ext_Pos .. Name'Last) = ".gif"
or Name (Ext_Pos .. Name'Last) = ".xbm"
or Name (Ext_Pos .. Name'Last) = ".png" then
return IMAGE;
elsif Name (Ext_Pos .. Name'Last) = ".zip"
or Name (Ext_Pos .. Name'Last) = ".jar" then
return ZIP;
elsif Name (Ext_Pos .. Name'Last) = ".pdf" then
return PDF;
end if;
end if;
return UNKNOWN;
end;
end Get_File_Type;
-- ------------------------------
-- Called by the servlet container when a POST request is received.
-- Receives the uploaded files and identify them using some external command.
-- ------------------------------
procedure Do_Post (Server : in Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server);
procedure Process_Part (Part : in ASF.Parts.Part'Class);
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
procedure Process_Part (Part : in ASF.Parts.Part'Class) is
Name : constant String := Part.Get_Name;
Content_Type : constant String := Part.Get_Content_Type;
Path : constant String := Part.Get_Local_Filename;
Kind : constant File_Type := Get_File_Type (Content_Type, Name);
begin
Output.Write ("<tr><td>Name: " & Name);
Output.Write ("</td><td>Content_Type: " & Content_Type & "</td>");
Output.Write ("<td>Path: " & Path & "</td>");
Output.Write ("<td>Length: " & Natural'Image (Part.Get_Size) & "</td>");
Output.Write ("</tr><tr><td></td><td colspan='3'><pre>");
case Kind is
when TAR_GZ =>
Execute ("tar tvzf " & Path, Output);
when TAR =>
Execute ("tar tvf " & Path, Output);
when IMAGE =>
Execute ("identify " & Path, Output);
when ZIP =>
Execute ("zipinfo " & Path, Output);
when PDF =>
Execute ("pdfinfo " & Path, Output);
when others =>
Output.Write ("Unknown file type");
end case;
Output.Write ("</pre></td></tr>");
end Process_Part;
begin
Response.Set_Content_Type ("text/html");
Output.Write ("<html><body>");
Output.Write ("<table style='width: 100%;'>");
for I in 1 .. Request.Get_Part_Count loop
Request.Process_Part (I, Process_Part'Access);
end loop;
Output.Write ("<tr><td colspan='5'><a href='upload.html'>Upload new files</a></td></tr>");
Output.Write ("</table>");
Output.Write ("</body></html>");
end Do_Post;
end Upload_Servlet;
|
-----------------------------------------------------------------------
-- upload_servlet -- Servlet example to upload files on the server
-- Copyright (C) 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Util.Streams.Pipes;
with Util.Strings;
with ASF.Parts;
package body Upload_Servlet is
-- ------------------------------
-- Write the upload form page with an optional response message.
-- ------------------------------
procedure Write (Response : in out Responses.Response'Class;
Message : in String) is
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Output.Write ("<html><head><title>Upload servlet example</title></head>"
& "<style></style>"
& "<body>"
& "<h1>Upload files to identify them</h1>");
-- Display the response or some error.
if Message /= "" then
Output.Write ("<h2>" & Message & "</h2>");
end if;
-- Render the form. If we have some existing Radius or Height
-- use them to set the initial values.
Output.Write ("<p>Identifies images, PDF, tar, tar.gz, zip</p>"
& "<form method='post' enctype='multipart/form-data'>"
& "<table>"
& "<tr><td>File 1</td>"
& "<td><input type='file' size='50' name='file1' maxlength='100000'/></td>"
& "</tr><tr><td>File 2</td>"
& "<td><input type='file' size='50' name='file2' maxlength='100000'/></td>"
& "</tr><tr><td>File 3</td>"
& "<td><input type='file' size='50' name='file3' maxlength='100000'/></td>"
& "</tr>"
& "<tr><td></td><td><input type='submit' value='Identify'></input></td></tr>"
& "</table></form>"
& "</body></html>");
Response.Set_Status (Responses.SC_OK);
end Write;
-- ------------------------------
-- Called by the servlet container when a GET request is received.
-- Display the volume form page.
-- ------------------------------
procedure Do_Get (Server : in Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server, Request);
begin
Write (Response, "");
end Do_Get;
-- ------------------------------
-- Execute a command and write the result to the output stream.
-- ------------------------------
procedure Execute (Command : in String;
Output : in out ASF.Streams.Print_Stream) is
use type Ada.Streams.Stream_Element_Offset;
Proc : Util.Streams.Pipes.Pipe_Stream;
Content : Ada.Streams.Stream_Element_Array (0 .. 1024);
Pos : Ada.Streams.Stream_Element_Offset;
begin
Proc.Open (Command);
loop
Proc.Read (Into => Content,
Last => Pos);
exit when Pos < 0;
Output.Write (Content (0 .. Pos));
end loop;
Proc.Close;
if Proc.Get_Exit_Status /= 0 then
Output.Write ("Command '" & Command & "' exited with code "
& Integer'Image (Proc.Get_Exit_Status));
end if;
end Execute;
-- ------------------------------
-- Guess a file type depending on a content type or a file name.
-- ------------------------------
function Get_File_Type (Content_Type : in String;
Name : in String) return File_Type is
begin
if Content_Type = "application/pdf" then
return PDF;
elsif Content_Type = "image/png" or Content_Type = "image/jpeg" then
return IMAGE;
elsif Content_Type = "image/gif" then
return IMAGE;
elsif Content_Type = "application/zip" then
return ZIP;
end if;
declare
Ext_Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Ext_Pos > 0 then
if Name (Ext_Pos .. Name'Last) = ".gz" or Name (Ext_Pos .. Name'Last) = ".tgz" then
return TAR_GZ;
elsif Name (Ext_Pos .. Name'Last) = ".tar" then
return TAR;
elsif Name (Ext_Pos .. Name'Last) = ".jpg"
or Name (Ext_Pos .. Name'Last) = ".gif"
or Name (Ext_Pos .. Name'Last) = ".xbm"
or Name (Ext_Pos .. Name'Last) = ".png"
then
return IMAGE;
elsif Name (Ext_Pos .. Name'Last) = ".zip"
or Name (Ext_Pos .. Name'Last) = ".jar"
then
return ZIP;
elsif Name (Ext_Pos .. Name'Last) = ".pdf" then
return PDF;
end if;
end if;
return UNKNOWN;
end;
end Get_File_Type;
-- ------------------------------
-- Called by the servlet container when a POST request is received.
-- Receives the uploaded files and identify them using some external command.
-- ------------------------------
procedure Do_Post (Server : in Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server);
procedure Process_Part (Part : in ASF.Parts.Part'Class);
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
procedure Process_Part (Part : in ASF.Parts.Part'Class) is
Name : constant String := Part.Get_Name;
Content_Type : constant String := Part.Get_Content_Type;
Path : constant String := Part.Get_Local_Filename;
Kind : constant File_Type := Get_File_Type (Content_Type, Name);
begin
Output.Write ("<tr><td>Name: " & Name);
Output.Write ("</td><td>Content_Type: " & Content_Type & "</td>");
Output.Write ("<td>Path: " & Path & "</td>");
Output.Write ("<td>Length: " & Natural'Image (Part.Get_Size) & "</td>");
Output.Write ("</tr><tr><td></td><td colspan='3'><pre>");
case Kind is
when TAR_GZ =>
Execute ("tar tvzf " & Path, Output);
when TAR =>
Execute ("tar tvf " & Path, Output);
when IMAGE =>
Execute ("identify " & Path, Output);
when ZIP =>
Execute ("zipinfo " & Path, Output);
when PDF =>
Execute ("pdfinfo " & Path, Output);
when others =>
Output.Write ("Unknown file type");
end case;
Output.Write ("</pre></td></tr>");
end Process_Part;
begin
Response.Set_Content_Type ("text/html");
Output.Write ("<html><body>");
Output.Write ("<table style='width: 100%;'>");
for I in 1 .. Request.Get_Part_Count loop
Request.Process_Part (I, Process_Part'Access);
end loop;
Output.Write ("<tr><td colspan='5'><a href='upload.html'>Upload new files</a></td></tr>");
Output.Write ("</table>");
Output.Write ("</body></html>");
end Do_Post;
end Upload_Servlet;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
eafb392824a5b8f821a257c5ba4484e3e3197730
|
mat/src/mat-formats.adb
|
mat/src/mat-formats.adb
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body MAT.Formats is
use type MAT.Types.Target_Tick_Ref;
Hex_Prefix : Boolean := True;
Conversion : constant String (1 .. 10) := "0123456789";
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value);
begin
if Hex_Prefix then
return "0x" & Hex;
else
return Hex;
end if;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
-- ------------------------------
-- Format the time relative to the start time.
-- ------------------------------
function Time (Value : in MAT.Types.Target_Tick_Ref;
Start : in MAT.Types.Target_Tick_Ref) return String is
T : constant MAT.Types.Target_Tick_Ref := Value - Start;
Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Frac : String (1 .. 5);
begin
Frac (5) := 's';
Frac (4) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (3) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (2) := Conversion (Msec mod 10 + 1);
Frac (1) := '.';
return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac;
end Time;
-- ------------------------------
-- Format the duration in seconds, milliseconds or microseconds.
-- ------------------------------
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is
Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Val : Natural;
Frac : String (1 .. 5);
begin
if Sec = 0 and Msec = 0 then
return Util.Strings.Image (Integer (Usec)) & "us";
elsif Sec = 0 then
Val := Natural (Usec mod 1_000);
Frac (5) := 's';
Frac (4) := 'm';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac;
else
Val := Msec;
Frac (4) := 's';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac (1 .. 4);
end if;
end Duration;
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is
Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward);
Len : constant Natural := Ada.Strings.Unbounded.Length (File);
begin
if Pos /= 0 then
return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len);
else
return Ada.Strings.Unbounded.To_String (File);
end if;
end Location;
-- ------------------------------
-- Format a file, line, function information into a string.
-- ------------------------------
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String is
begin
if Ada.Strings.Unbounded.Length (File) = 0 then
return Ada.Strings.Unbounded.To_String (Func);
elsif Line > 0 then
declare
Num : constant String := Natural'Image (Line);
begin
return Ada.Strings.Unbounded.To_String (Func) & " ("
& Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")";
end;
else
return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")";
end if;
end Location;
function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is
begin
case Item.Index is
when MAT.Events.Targets.MSG_MALLOC =>
return Size (Item.Size) & " bytes allocated";
when MAT.Events.Targets.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.Targets.MSG_FREE =>
return Size (Item.Size) & " bytes freed";
when others =>
return "unknown";
end case;
end Event;
function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type;
Related : in MAT.Events.Targets.Target_Event_Vector) return String is
Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First;
Free_Event : MAT.Events.Targets.Probe_Event_Type;
begin
Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE);
return Size (Item.Size) & " bytes allocated, " & Duration (Free_Event.Time - Item.Time);
exception
when MAT.Events.Targets.Not_Found =>
return Size (Item.Size) & " bytes allocated";
end Event_Malloc;
-- Format a short description of the event.
function Event (Item : in MAT.Events.Targets.Probe_Event_Type;
Related : in MAT.Events.Targets.Target_Event_Vector) return String is
begin
case Item.Index is
when MAT.Events.Targets.MSG_MALLOC =>
return Event_Malloc (Item, Related);
when MAT.Events.Targets.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.Targets.MSG_FREE =>
return Size (Item.Size) & " bytes freed";
when MAT.Events.Targets.MSG_BEGIN =>
return "Begin event";
when MAT.Events.Targets.MSG_END =>
return "End event";
when MAT.Events.Targets.MSG_LIBRARY =>
return "Library information event";
when others =>
return "unknown";
end case;
end Event;
end MAT.Formats;
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body MAT.Formats is
use type MAT.Types.Target_Tick_Ref;
Hex_Prefix : Boolean := True;
Conversion : constant String (1 .. 10) := "0123456789";
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value);
begin
if Hex_Prefix then
return "0x" & Hex;
else
return Hex;
end if;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
-- ------------------------------
-- Format the time relative to the start time.
-- ------------------------------
function Time (Value : in MAT.Types.Target_Tick_Ref;
Start : in MAT.Types.Target_Tick_Ref) return String is
T : constant MAT.Types.Target_Tick_Ref := Value - Start;
Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Frac : String (1 .. 5);
begin
Frac (5) := 's';
Frac (4) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (3) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (2) := Conversion (Msec mod 10 + 1);
Frac (1) := '.';
return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac;
end Time;
-- ------------------------------
-- Format the duration in seconds, milliseconds or microseconds.
-- ------------------------------
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is
Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Val : Natural;
Frac : String (1 .. 5);
begin
if Sec = 0 and Msec = 0 then
return Util.Strings.Image (Integer (Usec)) & "us";
elsif Sec = 0 then
Val := Natural (Usec mod 1_000);
Frac (5) := 's';
Frac (4) := 'm';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac;
else
Val := Msec;
Frac (4) := 's';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac (1 .. 4);
end if;
end Duration;
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is
Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward);
Len : constant Natural := Ada.Strings.Unbounded.Length (File);
begin
if Pos /= 0 then
return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len);
else
return Ada.Strings.Unbounded.To_String (File);
end if;
end Location;
-- ------------------------------
-- Format a file, line, function information into a string.
-- ------------------------------
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String is
begin
if Ada.Strings.Unbounded.Length (File) = 0 then
return Ada.Strings.Unbounded.To_String (Func);
elsif Line > 0 then
declare
Num : constant String := Natural'Image (Line);
begin
return Ada.Strings.Unbounded.To_String (Func) & " ("
& Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")";
end;
else
return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")";
end if;
end Location;
function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is
begin
case Item.Index is
when MAT.Events.Targets.MSG_MALLOC =>
return Size (Item.Size) & " bytes allocated";
when MAT.Events.Targets.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.Targets.MSG_FREE =>
return Size (Item.Size) & " bytes freed";
when others =>
return "unknown";
end case;
end Event;
function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type;
Related : in MAT.Events.Targets.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First;
Free_Event : MAT.Events.Targets.Probe_Event_Type;
begin
Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE);
return Size (Item.Size) & " bytes allocated, @" & Duration (Free_Event.Time - Start_Time)
& " freed " & Duration (Free_Event.Time - Item.Time) & " after"
;
exception
when MAT.Events.Targets.Not_Found =>
return Size (Item.Size) & " bytes allocated";
end Event_Malloc;
-- Format a short description of the event.
function Event (Item : in MAT.Events.Targets.Probe_Event_Type;
Related : in MAT.Events.Targets.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
case Item.Index is
when MAT.Events.Targets.MSG_MALLOC =>
return Event_Malloc (Item, Related, Start_Time);
when MAT.Events.Targets.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.Targets.MSG_FREE =>
return Size (Item.Size) & " bytes freed";
when MAT.Events.Targets.MSG_BEGIN =>
return "Begin event";
when MAT.Events.Targets.MSG_END =>
return "End event";
when MAT.Events.Targets.MSG_LIBRARY =>
return "Library information event";
when others =>
return "unknown";
end case;
end Event;
end MAT.Formats;
|
Print the relative time when the event was raised and print the duration for the memory slot allocation
|
Print the relative time when the event was raised and print the duration for the memory slot allocation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
1bea6b225b81f8bf39869ffce8ff65f046937cb4
|
src/asf-servlets-mappers.adb
|
src/asf-servlets-mappers.adb
|
-----------------------------------------------------------------------
-- asf-servlets-mappers -- Read servlet configuration files
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Utils;
package body ASF.Servlets.Mappers is
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the <b>FILTER_MAPPING</b>, <b>SERVLET_MAPPING</b> or <b>CONTEXT_PARAM</b> field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
-- <context-param>
-- <param-name>property</param-name>
-- <param-value>false</param-value>
-- </context-param>
-- <filter-mapping>
-- <filter-name>Dump Filter</filter-name>
-- <servlet-name>Faces Servlet</servlet-name>
-- </filter-mapping>
case Field is
when FILTER_NAME =>
N.Filter_Name := Value;
when SERVLET_NAME =>
N.Servlet_Name := Value;
when URL_PATTERN =>
N.URL_Pattern := Value;
when PARAM_NAME =>
N.Param_Name := Value;
when PARAM_VALUE =>
N.Param_Value := EL.Utils.Eval (To_String (Value), N.Context.all);
when MIME_TYPE =>
N.Mime_Type := Value;
when EXTENSION =>
N.Extension := Value;
when ERROR_CODE =>
N.Error_Code := Value;
when LOCATION =>
N.Location := Value;
when FILTER_MAPPING =>
N.Handler.Add_Filter_Mapping (Pattern => To_String (N.URL_Pattern),
Name => To_String (N.Filter_Name));
when SERVLET_MAPPING =>
N.Handler.Add_Mapping (Pattern => To_String (N.URL_Pattern),
Name => To_String (N.Servlet_Name));
when CONTEXT_PARAM =>
declare
Name : constant String := To_String (N.Param_Name);
begin
-- If the context parameter already has a value, do not set it again.
-- The value comes from an application setting and we want to keep it.
if N.Handler.Get_Init_Parameter (Name) = "" then
if Util.Beans.Objects.Is_Null (N.Param_Value) then
N.Handler.Set_Init_Parameter (Name => Name,
Value => "");
else
N.Handler.Set_Init_Parameter (Name => Name,
Value => To_String (N.Param_Value));
end if;
end if;
end;
when MIME_MAPPING =>
null;
when ERROR_PAGE =>
N.Handler.Set_Error_Page (Error => To_Integer (N.Error_Code),
Page => To_String (N.Location));
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>,
-- <b>filter-mapping</b> and <b>servlet-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("faces-config", SMapper'Access);
Reader.Add_Mapping ("module", SMapper'Access);
Reader.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("filter-mapping", FILTER_MAPPING);
SMapper.Add_Mapping ("filter-mapping/filter-name", FILTER_NAME);
SMapper.Add_Mapping ("filter-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("filter-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("servlet-mapping", SERVLET_MAPPING);
SMapper.Add_Mapping ("servlet-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("servlet-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("context-param", CONTEXT_PARAM);
SMapper.Add_Mapping ("context-param/param-name", PARAM_NAME);
SMapper.Add_Mapping ("context-param/param-value", PARAM_VALUE);
SMapper.Add_Mapping ("error-page", ERROR_PAGE);
SMapper.Add_Mapping ("error-page/error-code", ERROR_CODE);
SMapper.Add_Mapping ("error-page/location", LOCATION);
end ASF.Servlets.Mappers;
|
-----------------------------------------------------------------------
-- asf-servlets-mappers -- Read servlet configuration files
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with EL.Utils;
package body ASF.Servlets.Mappers is
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the <b>FILTER_MAPPING</b>, <b>SERVLET_MAPPING</b> or <b>CONTEXT_PARAM</b> field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
use type Ada.Containers.Count_Type;
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object);
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String);
procedure Add_Filter (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Filter_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Filter_Name));
end Add_Filter;
procedure Add_Mapping (Pattern : in Util.Beans.Objects.Object) is
begin
N.Handler.Add_Mapping (Pattern => To_String (Pattern),
Name => To_String (N.Servlet_Name));
end Add_Mapping;
procedure Add_Mapping (Handler : access procedure (Pattern : in Util.Beans.Objects.Object);
Message : in String) is
Last : constant Ada.Containers.Count_Type := N.URL_Patterns.Length;
begin
if Last = 0 then
raise Util.Serialize.Mappers.Field_Error with Message;
end if;
for I in 1 .. Last loop
N.URL_Patterns.Query_Element (Positive (I), Handler);
end loop;
N.URL_Patterns.Clear;
end Add_Mapping;
begin
-- <context-param>
-- <param-name>property</param-name>
-- <param-value>false</param-value>
-- </context-param>
-- <filter-mapping>
-- <filter-name>Dump Filter</filter-name>
-- <servlet-name>Faces Servlet</servlet-name>
-- </filter-mapping>
case Field is
when FILTER_NAME =>
N.Filter_Name := Value;
when SERVLET_NAME =>
N.Servlet_Name := Value;
when URL_PATTERN =>
N.URL_Patterns.Append (Value);
when PARAM_NAME =>
N.Param_Name := Value;
when PARAM_VALUE =>
N.Param_Value := EL.Utils.Eval (To_String (Value), N.Context.all);
when MIME_TYPE =>
N.Mime_Type := Value;
when EXTENSION =>
N.Extension := Value;
when ERROR_CODE =>
N.Error_Code := Value;
when LOCATION =>
N.Location := Value;
when FILTER_MAPPING =>
Add_Mapping (Add_Filter'Access, "Missing url-pattern for the filter mapping");
when SERVLET_MAPPING =>
Add_Mapping (Add_Mapping'Access, "Missing url-pattern for the servlet mapping");
when CONTEXT_PARAM =>
declare
Name : constant String := To_String (N.Param_Name);
begin
-- If the context parameter already has a value, do not set it again.
-- The value comes from an application setting and we want to keep it.
if N.Handler.Get_Init_Parameter (Name) = "" then
if Util.Beans.Objects.Is_Null (N.Param_Value) then
N.Handler.Set_Init_Parameter (Name => Name,
Value => "");
else
N.Handler.Set_Init_Parameter (Name => Name,
Value => To_String (N.Param_Value));
end if;
end if;
end;
when MIME_MAPPING =>
null;
when ERROR_PAGE =>
N.Handler.Set_Error_Page (Error => To_Integer (N.Error_Code),
Page => To_String (N.Location));
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>,
-- <b>filter-mapping</b> and <b>servlet-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("faces-config", SMapper'Access);
Reader.Add_Mapping ("module", SMapper'Access);
Reader.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("filter-mapping", FILTER_MAPPING);
SMapper.Add_Mapping ("filter-mapping/filter-name", FILTER_NAME);
SMapper.Add_Mapping ("filter-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("filter-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("servlet-mapping", SERVLET_MAPPING);
SMapper.Add_Mapping ("servlet-mapping/servlet-name", SERVLET_NAME);
SMapper.Add_Mapping ("servlet-mapping/url-pattern", URL_PATTERN);
SMapper.Add_Mapping ("context-param", CONTEXT_PARAM);
SMapper.Add_Mapping ("context-param/param-name", PARAM_NAME);
SMapper.Add_Mapping ("context-param/param-value", PARAM_VALUE);
SMapper.Add_Mapping ("error-page", ERROR_PAGE);
SMapper.Add_Mapping ("error-page/error-code", ERROR_CODE);
SMapper.Add_Mapping ("error-page/location", LOCATION);
end ASF.Servlets.Mappers;
|
Update the filter/servlet mapping configuration to allow the definition of several url-pattern for a filter/servlet mapping definition
|
Update the filter/servlet mapping configuration to allow the
definition of several url-pattern for a filter/servlet mapping definition
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
67f0689bebf49147e8ae5c6d8d30347a282037b3
|
regtests/security-permissions-tests.adb
|
regtests/security-permissions-tests.adb
|
-----------------------------------------------------------------------
-- Security-permissions-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
package body Security.Permissions.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Permissions");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Add_Permission",
Test_Add_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index",
Test_Add_Permission'Access);
end Add_Tests;
-- ------------------------------
-- Test Add_Permission and Get_Permission_Index
-- ------------------------------
procedure Test_Add_Permission (T : in out Test) is
Index1, Index2 : Permission_Index;
begin
Add_Permission ("test-create-permission", Index1);
T.Assert (Index1 = Get_Permission_Index ("test-create-permission"),
"Get_Permission_Index failed");
Add_Permission ("test-create-permission", Index2);
T.Assert (Index2 = Index1,
"Add_Permission failed");
end Test_Add_Permission;
end Security.Permissions.Tests;
|
-----------------------------------------------------------------------
-- 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;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
package body Security.Permissions.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Permissions");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Add_Permission",
Test_Add_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index",
Test_Add_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Definition",
Test_Define_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index (invalid name)",
Test_Get_Invalid_Permission'Access);
end Add_Tests;
-- ------------------------------
-- Test Add_Permission and Get_Permission_Index
-- ------------------------------
procedure Test_Add_Permission (T : in out Test) is
Index1, Index2 : Permission_Index;
begin
Add_Permission ("test-create-permission", Index1);
T.Assert (Index1 = Get_Permission_Index ("test-create-permission"),
"Get_Permission_Index failed");
Add_Permission ("test-create-permission", Index2);
T.Assert (Index2 = Index1,
"Add_Permission failed");
end Test_Add_Permission;
-- ------------------------------
-- Test the permission created by the Definition package.
-- ------------------------------
procedure Test_Define_Permission (T : in out Test) is
Index : Permission_Index;
begin
Index := Get_Permission_Index ("admin");
T.Assert (P_Admin.Permission = Index, "Invalid permission for admin");
Index := Get_Permission_Index ("create");
T.Assert (P_Create.Permission = Index, "Invalid permission for create");
Index := Get_Permission_Index ("update");
T.Assert (P_Update.Permission = Index, "Invalid permission for update");
Index := Get_Permission_Index ("delete");
T.Assert (P_Delete.Permission = Index, "Invalid permission for delete");
T.Assert (P_Admin.Permission /= P_Create.Permission, "Admin or create permission invalid");
T.Assert (P_Admin.Permission /= P_Update.Permission, "Admin or update permission invalid");
T.Assert (P_Admin.Permission /= P_Delete.Permission, "Admin or delete permission invalid");
T.Assert (P_Create.Permission /= P_Update.Permission, "Create or update permission invalid");
T.Assert (P_Create.Permission /= P_Delete.Permission, "Create or delete permission invalid");
T.Assert (P_Update.Permission /= P_Delete.Permission, "Create or delete permission invalid");
end Test_Define_Permission;
-- ------------------------------
-- Test Get_Permission on invalid permission name.
-- ------------------------------
procedure Test_Get_Invalid_Permission (T : in out Test) is
Index : Permission_Index;
begin
Index := Get_Permission_Index ("invalid");
T.Assert (Index = Index - 1,
"No exception raised by Get_Permission_Index for an invalid name");
exception
when Invalid_Name =>
null;
end Test_Get_Invalid_Permission;
end Security.Permissions.Tests;
|
Implement the new unit tests for Permissions.Definition package
|
Implement the new unit tests for Permissions.Definition package
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
fb9cf6042f4a402a38f675f7a003e8479df715b0
|
regtests/ado-parameters-tests.adb
|
regtests/ado-parameters-tests.adb
|
-----------------------------------------------------------------------
-- ado-parameters-tests -- Test query parameters and SQL expansion
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
package body ADO.Parameters.Tests is
use Util.Tests;
type Dialect is new ADO.Drivers.Dialects.Dialect with null record;
-- Check if the string is a reserved keyword.
overriding
function Is_Reserved (D : in Dialect;
Name : in String) return Boolean;
-- Test the Add_Param operation for various types.
generic
type T (<>) is private;
with procedure Add_Param (L : in out ADO.Parameters.Abstract_List;
V : in T) is <>;
Value : T;
Name : String;
procedure Test_Add_Param_T (Tst : in out Test);
-- Test the Bind_Param operation for various types.
generic
type T (<>) is private;
with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List;
N : in String;
V : in T) is <>;
Value : T;
Name : String;
procedure Test_Bind_Param_T (Tst : in out Test);
-- Test the Add_Param operation for various types.
procedure Test_Add_Param_T (Tst : in out Test) is
Count : constant Positive := 100;
SQL : ADO.Parameters.List;
S : Util.Measures.Stamp;
begin
for I in 1 .. Count loop
Add_Param (ADO.Parameters.Abstract_List (SQL), Value);
end loop;
Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)");
Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name);
end Test_Add_Param_T;
-- Test the Bind_Param operation for various types.
procedure Test_Bind_Param_T (Tst : in out Test) is
Count : constant Positive := 100;
SQL : ADO.Parameters.List;
S : Util.Measures.Stamp;
begin
for I in 1 .. Count loop
Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value);
end loop;
Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)");
Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name);
end Test_Bind_Param_T;
procedure Test_Add_Param_Integer is
new Test_Add_Param_T (Integer, Add_Param, 10, "Integer");
procedure Test_Add_Param_Identifier is
new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier");
procedure Test_Add_Param_Boolean is
new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean");
procedure Test_Add_Param_String is
new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String");
procedure Test_Add_Param_Calendar is
new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time");
procedure Test_Add_Param_Unbounded_String is
new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"),
"Unbounded_String");
procedure Test_Bind_Param_Integer is
new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer");
procedure Test_Bind_Param_Identifier is
new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier");
procedure Test_Bind_Param_Boolean is
new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean");
procedure Test_Bind_Param_String is
new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String");
procedure Test_Bind_Param_Calendar is
new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time");
procedure Test_Bind_Param_Unbounded_String is
new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"),
"Unbounded_String");
package Caller is new Util.Test_Caller (Test, "ADO.Parameters");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand",
Test_Expand_Sql'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)",
Test_Expand_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)",
Test_Expand_Perf'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)",
Test_Add_Param_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)",
Test_Add_Param_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)",
Test_Add_Param_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)",
Test_Add_Param_Calendar'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)",
Test_Add_Param_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)",
Test_Add_Param_Unbounded_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)",
Test_Bind_Param_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)",
Test_Bind_Param_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)",
Test_Bind_Param_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)",
Test_Bind_Param_Calendar'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)",
Test_Bind_Param_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)",
Test_Bind_Param_Unbounded_String'Access);
end Add_Tests;
-- ------------------------------
-- Check if the string is a reserved keyword.
-- ------------------------------
overriding
function Is_Reserved (D : in Dialect;
Name : in String) return Boolean is
begin
return False;
end Is_Reserved;
-- ------------------------------
-- Test expand SQL with parameters.
-- ------------------------------
procedure Test_Expand_Sql (T : in out Test) is
SQL : ADO.Parameters.List;
D : aliased Dialect;
procedure Check (Pattern : in String; Expect : in String);
procedure Check (Pattern : in String; Expect : in String) is
Result : constant String := SQL.Expand (Pattern);
begin
Assert_Equals (T, Expect, Result, "Invalid SQL expansion");
end Check;
begin
SQL.Set_Dialect (D'Unchecked_Access);
SQL.Bind_Param (1, "select '");
SQL.Bind_Param (2, "from");
SQL.Bind_Param ("user_id", String '("23"));
SQL.Bind_Param ("object_23_identifier", Integer (44));
SQL.Bind_Param ("bool", True);
SQL.Bind_Param (6, False);
SQL.Bind_Param ("_date", Ada.Calendar.Clock);
SQL.Bind_Null_Param ("_null");
Check ("?", "'select '''");
Check (":2", "'from'");
Check (":6", "0");
Check (":user_id", "'23'");
Check (":bool", "1");
Check (":_null", "NULL");
Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0");
Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0");
Check ("select ? :2 :user_id :object_23_identifier :bool :6",
"select 'select ''' 'from' '23' 44 1 0");
end Test_Expand_Sql;
-- ------------------------------
-- Test expand with invalid parameters.
-- ------------------------------
procedure Test_Expand_Error (T : in out Test) is
SQL : ADO.Parameters.List;
procedure Check (Pattern : in String; Expect : in String);
procedure Check (Pattern : in String; Expect : in String) is
Result : constant String := SQL.Expand (Pattern);
begin
Assert_Equals (T, Expect, Result, "Invalid SQL expansion");
end Check;
begin
Check (":<", "<");
Check (":234", "");
Check (":name", "");
Check ("select :", "select :");
end Test_Expand_Error;
-- ------------------------------
-- Test expand performance.
-- ------------------------------
procedure Test_Expand_Perf (T : in out Test) is
pragma Unreferenced (T);
SQL : ADO.Parameters.List;
D : aliased Dialect;
begin
SQL.Set_Dialect (D'Unchecked_Access);
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
SQL.Bind_Param (I, I);
end loop;
Util.Measures.Report (T, "Bind_Param (1000 calls)");
end;
declare
B : constant Unbounded_String
:= To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = 23");
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := To_String (B);
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand reference To_String");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = 23");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = :10");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)");
end;
end Test_Expand_Perf;
end ADO.Parameters.Tests;
|
-----------------------------------------------------------------------
-- ado-parameters-tests -- Test query parameters and SQL expansion
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
package body ADO.Parameters.Tests is
use Util.Tests;
type Dialect is new ADO.Drivers.Dialects.Dialect with null record;
-- Check if the string is a reserved keyword.
overriding
function Is_Reserved (D : in Dialect;
Name : in String) return Boolean;
-- Test the Add_Param operation for various types.
generic
type T (<>) is private;
with procedure Add_Param (L : in out ADO.Parameters.Abstract_List;
V : in T) is <>;
Value : T;
Name : String;
procedure Test_Add_Param_T (Tst : in out Test);
-- Test the Bind_Param operation for various types.
generic
type T (<>) is private;
with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List;
N : in String;
V : in T) is <>;
Value : T;
Name : String;
procedure Test_Bind_Param_T (Tst : in out Test);
-- Test the Add_Param operation for various types.
procedure Test_Add_Param_T (Tst : in out Test) is
Count : constant Positive := 100;
SQL : ADO.Parameters.List;
S : Util.Measures.Stamp;
begin
for I in 1 .. Count loop
Add_Param (ADO.Parameters.Abstract_List (SQL), Value);
end loop;
Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)");
Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name);
end Test_Add_Param_T;
-- Test the Bind_Param operation for various types.
procedure Test_Bind_Param_T (Tst : in out Test) is
Count : constant Positive := 100;
SQL : ADO.Parameters.List;
S : Util.Measures.Stamp;
begin
for I in 1 .. Count loop
Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value);
end loop;
Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)");
Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name);
end Test_Bind_Param_T;
procedure Test_Add_Param_Integer is
new Test_Add_Param_T (Integer, Add_Param, 10, "Integer");
procedure Test_Add_Param_Identifier is
new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier");
procedure Test_Add_Param_Boolean is
new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean");
procedure Test_Add_Param_String is
new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String");
procedure Test_Add_Param_Calendar is
new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time");
procedure Test_Add_Param_Unbounded_String is
new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"),
"Unbounded_String");
procedure Test_Bind_Param_Integer is
new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer");
procedure Test_Bind_Param_Identifier is
new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier");
procedure Test_Bind_Param_Boolean is
new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean");
procedure Test_Bind_Param_String is
new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String");
procedure Test_Bind_Param_Calendar is
new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time");
procedure Test_Bind_Param_Unbounded_String is
new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"),
"Unbounded_String");
package Caller is new Util.Test_Caller (Test, "ADO.Parameters");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand",
Test_Expand_Sql'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)",
Test_Expand_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)",
Test_Expand_Perf'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)",
Test_Add_Param_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)",
Test_Add_Param_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)",
Test_Add_Param_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)",
Test_Add_Param_Calendar'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)",
Test_Add_Param_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)",
Test_Add_Param_Unbounded_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)",
Test_Bind_Param_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)",
Test_Bind_Param_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)",
Test_Bind_Param_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)",
Test_Bind_Param_Calendar'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)",
Test_Bind_Param_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)",
Test_Bind_Param_Unbounded_String'Access);
end Add_Tests;
-- ------------------------------
-- Check if the string is a reserved keyword.
-- ------------------------------
overriding
function Is_Reserved (D : in Dialect;
Name : in String) return Boolean is
pragma Unreferenced (D, Name);
begin
return False;
end Is_Reserved;
-- ------------------------------
-- Test expand SQL with parameters.
-- ------------------------------
procedure Test_Expand_Sql (T : in out Test) is
SQL : ADO.Parameters.List;
D : aliased Dialect;
procedure Check (Pattern : in String; Expect : in String);
procedure Check (Pattern : in String; Expect : in String) is
Result : constant String := SQL.Expand (Pattern);
begin
Assert_Equals (T, Expect, Result, "Invalid SQL expansion");
end Check;
begin
SQL.Set_Dialect (D'Unchecked_Access);
SQL.Bind_Param (1, "select '");
SQL.Bind_Param (2, "from");
SQL.Bind_Param ("user_id", String '("23"));
SQL.Bind_Param ("object_23_identifier", Integer (44));
SQL.Bind_Param ("bool", True);
SQL.Bind_Param (6, False);
SQL.Bind_Param ("_date", Ada.Calendar.Clock);
SQL.Bind_Null_Param ("_null");
Check ("?", "'select '''");
Check (":2", "'from'");
Check (":6", "0");
Check (":user_id", "'23'");
Check (":bool", "1");
Check (":_null", "NULL");
Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0");
Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0");
Check ("select ? :2 :user_id :object_23_identifier :bool :6",
"select 'select ''' 'from' '23' 44 1 0");
end Test_Expand_Sql;
-- ------------------------------
-- Test expand with invalid parameters.
-- ------------------------------
procedure Test_Expand_Error (T : in out Test) is
SQL : ADO.Parameters.List;
procedure Check (Pattern : in String; Expect : in String);
procedure Check (Pattern : in String; Expect : in String) is
Result : constant String := SQL.Expand (Pattern);
begin
Assert_Equals (T, Expect, Result, "Invalid SQL expansion");
end Check;
begin
Check (":<", "<");
Check (":234", "");
Check (":name", "");
Check ("select :", "select :");
end Test_Expand_Error;
-- ------------------------------
-- Test expand performance.
-- ------------------------------
procedure Test_Expand_Perf (T : in out Test) is
pragma Unreferenced (T);
SQL : ADO.Parameters.List;
D : aliased Dialect;
begin
SQL.Set_Dialect (D'Unchecked_Access);
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
SQL.Bind_Param (I, I);
end loop;
Util.Measures.Report (T, "Bind_Param (1000 calls)");
end;
declare
B : constant Unbounded_String
:= To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = 23");
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := To_String (B);
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand reference To_String");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = 23");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = :10");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)");
end;
end Test_Expand_Perf;
end ADO.Parameters.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
0093820bd2a9d8edda67eeda489d00f263f6dd3f
|
src/asf-components-html-pages.ads
|
src/asf-components-html-pages.ads
|
-----------------------------------------------------------------------
-- html-pages -- HTML Page Components
-- Copyright (C) 2011, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>Pages</b> package implements various components used when building an HTML page.
--
package ASF.Components.Html.Pages is
-- ------------------------------
-- Head Component
-- ------------------------------
type UIHead is new UIHtmlComponent with private;
-- Encode the HTML head element.
overriding
procedure Encode_Begin (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class);
-- Terminate the HTML head element. Before closing the head, generate the resource
-- links that have been queued for the head generation.
overriding
procedure Encode_End (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Body Component
-- ------------------------------
type UIBody is new UIHtmlComponent with private;
-- Encode the HTML body element.
overriding
procedure Encode_Begin (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class);
-- Terminate the HTML body element. Before closing the body, generate the inclusion
-- of differed resources (pending javascript, inclusion of javascript files)
overriding
procedure Encode_End (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Doctype Component
-- ------------------------------
type UIDoctype is new UIHtmlComponent with private;
-- Encode the DOCTYPE element.
overriding
procedure Encode_Begin (UI : in UIDoctype;
Context : in out Contexts.Faces.Faces_Context'Class);
private
type UIHead is new UIHtmlComponent with null record;
type UIBody is new UIHtmlComponent with record
Value : EL.Objects.Object;
end record;
type UIDoctype is new UIHtmlComponent with null record;
end ASF.Components.Html.Pages;
|
-----------------------------------------------------------------------
-- html-pages -- HTML Page Components
-- Copyright (C) 2011, 2014, 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.
-----------------------------------------------------------------------
-- The <b>Pages</b> package implements various components used when building an HTML page.
--
package ASF.Components.Html.Pages is
-- ------------------------------
-- Head Component
-- ------------------------------
type UIHead is new UIHtmlComponent with private;
-- Encode the HTML head element.
overriding
procedure Encode_Begin (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class);
-- Terminate the HTML head element. Before closing the head, generate the resource
-- links that have been queued for the head generation.
overriding
procedure Encode_End (UI : in UIHead;
Context : in out Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Body Component
-- ------------------------------
type UIBody is new UIHtmlComponent with private;
-- Encode the HTML body element.
overriding
procedure Encode_Begin (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class);
-- Terminate the HTML body element. Before closing the body, generate the inclusion
-- of differed resources (pending javascript, inclusion of javascript files)
overriding
procedure Encode_End (UI : in UIBody;
Context : in out Contexts.Faces.Faces_Context'Class);
-- ------------------------------
-- Stylesheet Component
-- ------------------------------
type UIOutputStylesheet is new UIHtmlComponent with private;
-- Encode the HTML link element.
overriding
procedure Encode_End (UI : in UIOutputStylesheet;
Context : in out Contexts.Faces.Faces_Context'Class);
function Get_Link (UI : in UIOutputStylesheet;
Context : in Faces_Context'Class) return String;
-- ------------------------------
-- Doctype Component
-- ------------------------------
type UIDoctype is new UIHtmlComponent with private;
-- Encode the DOCTYPE element.
overriding
procedure Encode_Begin (UI : in UIDoctype;
Context : in out Contexts.Faces.Faces_Context'Class);
private
type UIHead is new UIHtmlComponent with null record;
type UIBody is new UIHtmlComponent with record
Value : EL.Objects.Object;
end record;
type UIOutputStylesheet is new UIHtmlComponent with null record;
type UIDoctype is new UIHtmlComponent with null record;
end ASF.Components.Html.Pages;
|
Declare UIOutputStylesheet type for <h:outputStylesheet>
|
Declare UIOutputStylesheet type for <h:outputStylesheet>
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
24f73aac64dbfeedd60b2d1d833d54bd0b2ec6ff
|
src/security-permissions.adb
|
src/security-permissions.adb
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Log.Loggers;
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package body Security.Permissions is
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions");
-- A global map to translate a string to a permission index.
package Permission_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Permission_Index,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
protected type Global_Index is
-- Get the permission index
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
Map : Permission_Maps.Map;
Next_Index : Permission_Index := Permission_Index'First;
end Global_Index;
protected body Global_Index is
function Get_Permission_Index (Name : in String) return Permission_Index is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
return Permission_Maps.Element (Pos);
else
raise Invalid_Name with "There is no permission '" & Name & "'";
end if;
end Get_Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index is
begin
return Next_Index;
end Get_Last_Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
Index := Permission_Maps.Element (Pos);
else
Index := Next_Index;
Log.Debug ("Creating permission index {1} for {0}",
Name, Permission_Index'Image (Index));
Map.Insert (Name, Index);
Next_Index := Next_Index + 1;
end if;
end Add_Permission;
end Global_Index;
Permission_Indexes : Global_Index;
-- ------------------------------
-- Get the permission index associated with the name.
-- ------------------------------
function Get_Permission_Index (Name : in String) return Permission_Index is
begin
return Permission_Indexes.Get_Permission_Index (Name);
end Get_Permission_Index;
-- ------------------------------
-- Get the last permission index registered in the global permission map.
-- ------------------------------
function Get_Last_Permission_Index return Permission_Index is
begin
return Permission_Indexes.Get_Last_Permission_Index;
end Get_Last_Permission_Index;
-- ------------------------------
-- Add the permission name and allocate a unique permission index.
-- ------------------------------
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
begin
Permission_Indexes.Add_Permission (Name, Index);
end Add_Permission;
package body Definition is
P : Permission_Index;
function Permission return Permission_Index is
begin
return P;
end Permission;
begin
Add_Permission (Name => Name, Index => P);
end Definition;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Log.Loggers;
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package body Security.Permissions is
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions");
-- A global map to translate a string to a permission index.
package Permission_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Permission_Index,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
protected type Global_Index is
-- Get the permission index
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
Map : Permission_Maps.Map;
Next_Index : Permission_Index := Permission_Index'First;
end Global_Index;
protected body Global_Index is
function Get_Permission_Index (Name : in String) return Permission_Index is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
return Permission_Maps.Element (Pos);
else
raise Invalid_Name with "There is no permission '" & Name & "'";
end if;
end Get_Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index is
begin
return Next_Index;
end Get_Last_Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
Index := Permission_Maps.Element (Pos);
else
Index := Next_Index;
Log.Debug ("Creating permission index {1} for {0}",
Name, Permission_Index'Image (Index));
Map.Insert (Name, Index);
Next_Index := Next_Index + 1;
end if;
end Add_Permission;
end Global_Index;
Permission_Indexes : Global_Index;
-- ------------------------------
-- Get the permission index associated with the name.
-- ------------------------------
function Get_Permission_Index (Name : in String) return Permission_Index is
begin
return Permission_Indexes.Get_Permission_Index (Name);
end Get_Permission_Index;
-- ------------------------------
-- Get the last permission index registered in the global permission map.
-- ------------------------------
function Get_Last_Permission_Index return Permission_Index is
begin
return Permission_Indexes.Get_Last_Permission_Index;
end Get_Last_Permission_Index;
-- ------------------------------
-- Add the permission name and allocate a unique permission index.
-- ------------------------------
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
begin
Permission_Indexes.Add_Permission (Name, Index);
end Add_Permission;
-- ------------------------------
-- Check if the permission index set contains the given permission index.
-- ------------------------------
function Has_Permission (Set : in Permission_Index_Set;
Index : in Permission_Index) return Boolean is
use Interfaces;
begin
return (Set (Natural (Index / 8)) and Shift_Left (1, Natural (Index mod 8))) /= 0;
end Has_Permission;
package body Definition is
P : Permission_Index;
function Permission return Permission_Index is
begin
return P;
end Permission;
begin
Add_Permission (Name => Name, Index => P);
end Definition;
end Security.Permissions;
|
Implement the Has_Permission function
|
Implement the Has_Permission function
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
81c0ae8069dc19147856480ff65bddf741ead03d
|
regtests/security-oauth-clients-tests.adb
|
regtests/security-oauth-clients-tests.adb
|
-----------------------------------------------------------------------
-- Security-oauth-clients-tests - Unit tests for OAuth
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with Util.Strings.Sets;
package body Security.OAuth.Clients.Tests is
package Caller is new Util.Test_Caller (Test, "Security.OAuth.Clients");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Create_Nonce",
Test_Create_Nonce'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Get_State",
Test_Get_State'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Is_Valid_State",
Test_Is_Valid_State'Access);
end Add_Tests;
-- ------------------------------
-- Test Create_Nonce operation.
-- ------------------------------
procedure Test_Create_Nonce (T : in out Test) is
Nonces : Util.Strings.Sets.Set;
begin
for I in 1 .. 1_000 loop
for I in 32 .. 734 loop
declare
S : constant String := Create_Nonce (I * 3);
begin
T.Assert (not Nonces.Contains (S), "Nonce was not unique: " & S);
Nonces.Include (S);
end;
end loop;
end loop;
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
Nonce : constant String := Create_Nonce (128);
pragma Unreferenced (Nonce);
begin
null;
end;
end loop;
Util.Measures.Report (S, "128 bits nonce generation (1000 calls)");
end;
end Test_Create_Nonce;
-- ------------------------------
-- Test the Get_State operation.
-- ------------------------------
procedure Test_Get_State (T : in out Test) is
App : Application;
Nonce : constant String := Create_Nonce (128);
begin
App.Set_Application_Identifier ("test");
Util.Tests.Assert_Equals (T, "test", App.Get_Application_Identifier, "Invalid application");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
App.Set_Provider_URI ("http://my-provider");
declare
State : constant String := App.Get_State (Nonce);
begin
T.Assert (State'Length > 25, "State is too small: " & State);
end;
end Test_Get_State;
-- ------------------------------
-- Test the Is_Valid_State operation.
-- ------------------------------
procedure Test_Is_Valid_State (T : in out Test) is
App : Application;
begin
App.Set_Application_Identifier ("test");
Util.Tests.Assert_Equals (T, "test", App.Get_Application_Identifier, "Invalid application");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
App.Set_Provider_URI ("http://my-provider");
for I in 1 .. 100 loop
declare
Nonce : constant String := Create_Nonce (128);
State : constant String := App.Get_State (Nonce);
begin
T.Assert (State'Length > 25, "State is too small: " & State);
T.Assert (App.Is_Valid_State (Nonce, State), "Invalid state: " & State);
T.Assert (not App.Is_Valid_State ("", State), "State was valid with invalid nonce");
T.Assert (not App.Is_Valid_State (State, State), "State must be invalid");
T.Assert (not App.Is_Valid_State (Nonce, State & "d"), "State must be invalid");
end;
end loop;
end Test_Is_Valid_State;
end Security.OAuth.Clients.Tests;
|
-----------------------------------------------------------------------
-- Security-oauth-clients-tests - Unit tests for OAuth
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Util.Test_Caller;
with Util.Measures;
with Util.Strings.Sets;
package body Security.OAuth.Clients.Tests is
package Caller is new Util.Test_Caller (Test, "Security.OAuth.Clients");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Create_Nonce",
Test_Create_Nonce'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Get_State",
Test_Get_State'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Is_Valid_State",
Test_Is_Valid_State'Access);
end Add_Tests;
-- ------------------------------
-- Test Create_Nonce operation.
-- ------------------------------
procedure Test_Create_Nonce (T : in out Test) is
Nonces : Util.Strings.Sets.Set;
begin
for I in 1 .. 1_000 loop
for I in 32 .. 734 loop
declare
S : constant String := Create_Nonce (I * 3);
begin
T.Assert (not Nonces.Contains (S), "Nonce was not unique: " & S);
Nonces.Include (S);
end;
end loop;
end loop;
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
Nonce : constant String := Create_Nonce (128);
pragma Unreferenced (Nonce);
begin
null;
end;
end loop;
Util.Measures.Report (S, "128 bits nonce generation (1000 calls)");
end;
end Test_Create_Nonce;
-- ------------------------------
-- Test the Get_State operation.
-- ------------------------------
procedure Test_Get_State (T : in out Test) is
App : Application;
Nonce : constant String := Create_Nonce (128);
begin
App.Set_Application_Identifier ("test");
Util.Tests.Assert_Equals (T, "test", App.Get_Application_Identifier, "Invalid application");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
App.Set_Provider_URI ("http://my-provider");
declare
State : constant String := App.Get_State (Nonce);
begin
T.Assert (State'Length > 25, "State is too small: " & State);
T.Assert (Ada.Strings.Fixed.Index (State, Nonce) = 0,
"The state must not contain the nonce");
-- Calling Get_State with the same nonce should produce the same result.
Util.Tests.Assert_Equals (T, State, App.Get_State (Nonce), "Invalid state");
App.Set_Application_Secret ("second-secret");
declare
State2 : constant String := App.Get_State (Nonce);
begin
T.Assert (State /= State2,
"Changing the application key should produce a different state");
end;
-- Restore the secret and change the callback.
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback2");
declare
State2 : constant String := App.Get_State (Nonce);
begin
T.Assert (State /= State2,
"Changing the application callback should produce a different state");
end;
-- Restore the callback and change the client Id.
App.Set_Application_Callback ("my-callback");
App.Set_Application_Identifier ("test2");
declare
State2 : constant String := App.Get_State (Nonce);
begin
T.Assert (State /= State2,
"Changing the application identifier should produce a different state");
end;
end;
end Test_Get_State;
-- ------------------------------
-- Test the Is_Valid_State operation.
-- ------------------------------
procedure Test_Is_Valid_State (T : in out Test) is
App : Application;
begin
App.Set_Application_Identifier ("test");
Util.Tests.Assert_Equals (T, "test", App.Get_Application_Identifier, "Invalid application");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
App.Set_Provider_URI ("http://my-provider");
for I in 1 .. 100 loop
declare
Nonce : constant String := Create_Nonce (128);
State : constant String := App.Get_State (Nonce);
begin
T.Assert (State'Length > 25, "State is too small: " & State);
T.Assert (App.Is_Valid_State (Nonce, State), "Invalid state: " & State);
T.Assert (not App.Is_Valid_State ("", State), "State was valid with invalid nonce");
T.Assert (not App.Is_Valid_State (State, State), "State must be invalid");
T.Assert (not App.Is_Valid_State (Nonce, State & "d"), "State must be invalid");
end;
end loop;
end Test_Is_Valid_State;
end Security.OAuth.Clients.Tests;
|
Add more tests for the Get_State generation
|
Add more tests for the Get_State generation
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
08050cd1dea10e5ec446f38ef843ede1b979f893
|
tests/natools-cron-tests.adb
|
tests/natools-cron-tests.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.Cron.Tests is
--------------------
-- Test Callbacks --
--------------------
overriding procedure Run (Self : in out Test_Callback) is
begin
Append (Self.Backend.all, Self.Symbol);
end Run;
overriding procedure Run (Self : in out Long_Callback) is
begin
Append (Self.Backend.all, Self.Open);
delay Self.Wait;
Append (Self.Backend.all, Self.Close);
end Run;
--------------------
-- Bounded String --
--------------------
procedure Append (S : in out Bounded_String; C : Character) is
begin
S.Size := S.Size + 1;
S.Data (S.Size) := C;
end Append;
function Get (S : Bounded_String) return String is
begin
return S.Data (1 .. S.Size);
end Get;
procedure Reset (S : in out Bounded_String) is
begin
S.Size := 0;
end Reset;
-----------------
-- Test Helper --
-----------------
function Quote (Data : String) return String
is ('"' & Data & '"');
procedure Check is new NT.Generic_Check (String, "=", Quote, False);
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Basic_Usage (Report);
Delete_While_Busy (Report);
Insert_While_Busy (Report);
Time_Collision (Report);
Delete_While_Collision (Report);
Event_List_Fusion (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Basic_Usage (Report : in out NT.Reporter'Class) is
use type Ada.Calendar.Time;
Test : NT.Test := Report.Item ("Basic black-box usage");
Total : constant Duration := 10.0;
Tick : constant Duration := Total / 10;
Half_Tick : constant Duration := Tick / 2;
Log : aliased Bounded_String (256);
begin
declare
Beat : constant Cron_Entry := Create
(Tick, Test_Callback'(Backend => Log'Access, Symbol => '.'));
pragma Unreferenced (Beat);
One_Time_Entry : constant Cron_Entry := Create
(Ada.Calendar.Clock + Half_Tick,
Test_Callback'(Backend => Log'Access, Symbol => 'o'));
pragma Unreferenced (One_Time_Entry);
Test_Entry : Cron_Entry;
begin
delay Half_Tick;
Test_Entry.Set
(Tick, Test_Callback'(Backend => Log'Access, Symbol => '1'));
delay 3 * Tick + Half_Tick;
Test_Entry.Reset;
delay Half_Tick;
end;
Append (Log, '|');
delay Tick / 10;
declare
Beat : constant Cron_Entry := Create
((Origin => Ada.Calendar.Clock + Half_Tick,
Period => Tick),
Test_Callback'(Backend => Log'Access, Symbol => '.'));
pragma Unreferenced (Beat);
One_Time_Entry : constant Cron_Entry := Create
((Origin => Ada.Calendar.Clock + Tick,
Period => -Half_Tick),
Test_Callback'(Backend => Log'Access, Symbol => 'O'));
pragma Unreferenced (One_Time_Entry);
Slow, Fast : Cron_Entry;
begin
Slow.Set
(2 * Tick,
Test_Callback'(Backend => Log'Access, Symbol => 's'));
delay 2 * Tick;
Fast.Set
(Tick / 5,
Test_Callback'(Backend => Log'Access, Symbol => 'f'));
delay Tick + Half_Tick;
Fast.Reset;
delay Tick + Half_Tick;
end;
-- Timeline, in ticks:
-- Beat: set at 0.0, finalized at 4.5, run at 1.0, 2.0, 3.0, 4.0.
-- Test_Entry: set at 0.5, reset at 4.0, run at 1.5, 2.5, 3.5.
-- Beat: set at 4.5, finalized at 9.5, run at 5.0, 6.0, 7.0, 8.0, 9.0.
-- Slow: set at 4.5, finalized at 9.5, run at 6.5, 8.5.
-- Fast: set at 6.5, reset at 8.0,
-- run at 6.7, 6.9, 7.1, 7.3, 7.5, 7.7, 7.9
Check (Test, Get (Log), "o.1.1.1.|.O.sff.fffff.s.");
exception
when Error : others => Test.Report_Exception (Error);
end Basic_Usage;
procedure Delete_While_Busy (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Delete entry while callback is running");
Total : constant Duration := 0.01;
Log : aliased Bounded_String (256);
begin
declare
Test_Entry : Cron_Entry;
begin
Test_Entry.Set (Total / 8, Long_Callback'
(Backend => Log'Access,
Open => '(',
Close => ')',
Wait => Total / 4));
delay Total / 4;
end;
Check (Test, Get (Log), "(", "Before wait");
delay Total / 2;
Check (Test, Get (Log), "()", "After wait");
exception
when Error : others => Test.Report_Exception (Error);
end Delete_While_Busy;
procedure Delete_While_Collision (Report : in out NT.Reporter'Class) is
Test : NT.Test
:= Report.Item ("Delete entry while callback list is running");
Total : constant Duration := 0.0625;
Tick : constant Duration := Total / 8;
Log : aliased Bounded_String (256);
begin
declare
use type Ada.Calendar.Time;
Common : constant Periodic_Time
:= (Origin => Ada.Calendar.Clock + 2 * Tick,
Period => 8 * Tick);
First, Second : Cron_Entry;
begin
First.Set (Common, Long_Callback'
(Backend => Log'Access,
Open => '(',
Close => ')',
Wait => 2 * Tick));
Second.Set (Common, Long_Callback'
(Backend => Log'Access,
Open => '<',
Close => '>',
Wait => 2 * Tick));
delay 3 * Tick;
end;
-- Timeline: 0 . 1/4 . 1/2 . 3/4 . 1 . 5/4
-- Triggers: * *
-- Log: ( )< > (
-- End of Block: ^
-- End of Test: ^
Check (Test, Get (Log), "(");
delay 4 * Tick;
Check (Test, Get (Log), "()<>");
exception
when Error : others => Test.Report_Exception (Error);
end Delete_While_Collision;
procedure Event_List_Fusion (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Fusion of synchronized callbacks");
Total : constant Duration := 0.25;
Log : aliased Bounded_String (256);
begin
declare
use type Ada.Calendar.Time;
First_Tick : constant Periodic_Time
:= (Origin => Ada.Calendar.Clock + Total / 8,
Period => Total / 4);
Second_Tick : constant Periodic_Time
:= (Origin => First_Tick.Origin + First_Tick.Period,
Period => First_Tick.Period);
A_Head, A_Tail, B_Head, B_Tail : Cron_Entry;
begin
A_Head.Set (First_Tick, Long_Callback'
(Backend => Log'Access,
Open => '(',
Close => ')',
Wait => Total / 8));
A_Tail.Set (First_Tick, Test_Callback'
(Backend => Log'Access,
Symbol => 'A'));
delay Total / 8 + Total / 16;
Check (Test, Get (Log), "(");
B_Head.Set (Second_Tick, Test_Callback'
(Backend => Log'Access,
Symbol => 'B'));
B_Tail.Set (Second_Tick, Test_Callback'
(Backend => Log'Access,
Symbol => 'b'));
delay Total / 4 + Total / 8;
Check (Test, Get (Log), "()ABb()A");
A_Tail.Reset;
B_Tail.Reset;
delay Total / 4;
Check (Test, Get (Log), "()ABb()AB()");
end;
-- Timeline: 0 . 1/4 . 1/2 . 3/4 . 1
-- Log: ( )A Bb( )A B( )
-- Code: * * * * *
delay Total / 8;
Check (Test, Get (Log), "()ABb()AB()");
exception
when Error : others => Test.Report_Exception (Error);
end Event_List_Fusion;
procedure Insert_While_Busy (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Insert entry while callback is running");
Total : constant Duration := 1.0;
Log : aliased Bounded_String (256);
begin
declare
Long, Short : Cron_Entry;
begin
Long.Set
(Total / 8,
Long_Callback'
(Backend => Log'Access,
Open => '(',
Close => ')',
Wait => Total / 5));
delay Total / 8 + Total / 16;
Short.Set
(Total / 8,
Test_Callback'(Backend => Log'Access, Symbol => '.'));
delay Total / 2 + Total / 8;
end;
-- Timeline: 0 . 1/8 . 1/4 . 3/8 . 1/2 . 5/8 . 3/4 . 7/8 . 1
-- Set: L S
-- Finalize: *
-- Ticks: L L S L S L S L S L
-- Run: <----L---->S <----L---->S <----L---->
delay Total / 8;
Check (Test, Get (Log), "().().()");
exception
when Error : others => Test.Report_Exception (Error);
end Insert_While_Busy;
procedure Time_Collision (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Simultaneous activation of events");
Total : constant Duration := 0.01;
Tick : constant Duration := Total / 4;
Log : aliased Bounded_String (256);
begin
declare
use type Ada.Calendar.Time;
Common : constant Periodic_Time := (Ada.Calendar.Clock + Tick, Tick);
First, Second, Third : Cron_Entry;
begin
First.Set
(Common, Test_Callback'(Backend => Log'Access, Symbol => '1'));
Second.Set
(Common, Test_Callback'(Backend => Log'Access, Symbol => '2'));
Third.Set
((Origin => Common.Origin, Period => 2 * Common.Period),
Test_Callback'(Backend => Log'Access, Symbol => '3'));
delay Total - Tick / 2;
end;
Check (Test, Get (Log), "12312123");
exception
when Error : others => Test.Report_Exception (Error);
end Time_Collision;
end Natools.Cron.Tests;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.Cron.Tests is
--------------------
-- Test Callbacks --
--------------------
overriding procedure Run (Self : in out Test_Callback) is
begin
Append (Self.Backend.all, Self.Symbol);
end Run;
overriding procedure Run (Self : in out Long_Callback) is
begin
Append (Self.Backend.all, Self.Open);
delay Self.Wait;
Append (Self.Backend.all, Self.Close);
end Run;
--------------------
-- Bounded String --
--------------------
procedure Append (S : in out Bounded_String; C : Character) is
begin
S.Size := S.Size + 1;
S.Data (S.Size) := C;
end Append;
function Get (S : Bounded_String) return String is
begin
return S.Data (1 .. S.Size);
end Get;
procedure Reset (S : in out Bounded_String) is
begin
S.Size := 0;
end Reset;
-----------------
-- Test Helper --
-----------------
function Quote (Data : String) return String
is ('"' & Data & '"');
procedure Check is new NT.Generic_Check (String, "=", Quote, False);
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Basic_Usage (Report);
Delete_While_Busy (Report);
Insert_While_Busy (Report);
Time_Collision (Report);
Delete_While_Collision (Report);
Event_List_Fusion (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Basic_Usage (Report : in out NT.Reporter'Class) is
use type Ada.Calendar.Time;
Test : NT.Test := Report.Item ("Basic black-box usage");
Total : constant Duration := 10.0;
Tick : constant Duration := Total / 10;
Half_Tick : constant Duration := Tick / 2;
Log : aliased Bounded_String (256);
begin
declare
Beat : constant Cron_Entry := Create
(Tick, Test_Callback'(Backend => Log'Access, Symbol => '.'));
pragma Unreferenced (Beat);
One_Time_Entry : constant Cron_Entry := Create
(Ada.Calendar.Clock + Half_Tick,
Test_Callback'(Backend => Log'Access, Symbol => 'o'));
pragma Unreferenced (One_Time_Entry);
Test_Entry : Cron_Entry;
begin
delay Half_Tick;
Test_Entry.Set
(Tick, Test_Callback'(Backend => Log'Access, Symbol => '1'));
delay 3 * Tick + Half_Tick;
Test_Entry.Reset;
delay Half_Tick;
end;
Append (Log, '|');
delay Tick / 10;
declare
Beat : constant Cron_Entry := Create
((Origin => Ada.Calendar.Clock + Half_Tick,
Period => Tick),
Test_Callback'(Backend => Log'Access, Symbol => '.'));
pragma Unreferenced (Beat);
One_Time_Entry : constant Cron_Entry := Create
((Origin => Ada.Calendar.Clock + Tick,
Period => -Half_Tick),
Test_Callback'(Backend => Log'Access, Symbol => 'O'));
pragma Unreferenced (One_Time_Entry);
Slow, Fast : Cron_Entry;
begin
Slow.Set
(2 * Tick,
Test_Callback'(Backend => Log'Access, Symbol => 's'));
delay 2 * Tick;
Fast.Set
(Tick / 5,
Test_Callback'(Backend => Log'Access, Symbol => 'f'));
delay Tick + Half_Tick;
Fast.Reset;
delay Tick + Half_Tick;
end;
-- Timeline, in ticks:
-- Beat: set at 0.0, finalized at 4.5, run at 1.0, 2.0, 3.0, 4.0.
-- Test_Entry: set at 0.5, reset at 4.0, run at 1.5, 2.5, 3.5.
-- Beat: set at 4.5, finalized at 9.5, run at 5.0, 6.0, 7.0, 8.0, 9.0.
-- Slow: set at 4.5, finalized at 9.5, run at 6.5, 8.5.
-- Fast: set at 6.5, reset at 8.0,
-- run at 6.7, 6.9, 7.1, 7.3, 7.5, 7.7, 7.9
Check (Test, "o.1.1.1.|.O.sff.fffff.s.", Get (Log));
exception
when Error : others => Test.Report_Exception (Error);
end Basic_Usage;
procedure Delete_While_Busy (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Delete entry while callback is running");
Total : constant Duration := 0.01;
Log : aliased Bounded_String (256);
begin
declare
Test_Entry : Cron_Entry;
begin
Test_Entry.Set (Total / 8, Long_Callback'
(Backend => Log'Access,
Open => '(',
Close => ')',
Wait => Total / 4));
delay Total / 4;
end;
Check (Test, "(", Get (Log), "Before wait");
delay Total / 2;
Check (Test, "()", Get (Log), "After wait");
exception
when Error : others => Test.Report_Exception (Error);
end Delete_While_Busy;
procedure Delete_While_Collision (Report : in out NT.Reporter'Class) is
Test : NT.Test
:= Report.Item ("Delete entry while callback list is running");
Total : constant Duration := 0.0625;
Tick : constant Duration := Total / 8;
Log : aliased Bounded_String (256);
begin
declare
use type Ada.Calendar.Time;
Common : constant Periodic_Time
:= (Origin => Ada.Calendar.Clock + 2 * Tick,
Period => 8 * Tick);
First, Second : Cron_Entry;
begin
First.Set (Common, Long_Callback'
(Backend => Log'Access,
Open => '(',
Close => ')',
Wait => 2 * Tick));
Second.Set (Common, Long_Callback'
(Backend => Log'Access,
Open => '<',
Close => '>',
Wait => 2 * Tick));
delay 3 * Tick;
end;
-- Timeline: 0 . 1/4 . 1/2 . 3/4 . 1 . 5/4
-- Triggers: * *
-- Log: ( )< > (
-- End of Block: ^
-- End of Test: ^
Check (Test, "(", Get (Log));
delay 4 * Tick;
Check (Test, "()<>", Get (Log));
exception
when Error : others => Test.Report_Exception (Error);
end Delete_While_Collision;
procedure Event_List_Fusion (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Fusion of synchronized callbacks");
Total : constant Duration := 0.25;
Log : aliased Bounded_String (256);
begin
declare
use type Ada.Calendar.Time;
First_Tick : constant Periodic_Time
:= (Origin => Ada.Calendar.Clock + Total / 8,
Period => Total / 4);
Second_Tick : constant Periodic_Time
:= (Origin => First_Tick.Origin + First_Tick.Period,
Period => First_Tick.Period);
A_Head, A_Tail, B_Head, B_Tail : Cron_Entry;
begin
A_Head.Set (First_Tick, Long_Callback'
(Backend => Log'Access,
Open => '(',
Close => ')',
Wait => Total / 8));
A_Tail.Set (First_Tick, Test_Callback'
(Backend => Log'Access,
Symbol => 'A'));
delay Total / 8 + Total / 16;
Check (Test, "(", Get (Log));
B_Head.Set (Second_Tick, Test_Callback'
(Backend => Log'Access,
Symbol => 'B'));
B_Tail.Set (Second_Tick, Test_Callback'
(Backend => Log'Access,
Symbol => 'b'));
delay Total / 4 + Total / 8;
Check (Test, "()ABb()A", Get (Log));
A_Tail.Reset;
B_Tail.Reset;
delay Total / 4;
Check (Test, "()ABb()AB()", Get (Log));
end;
-- Timeline: 0 . 1/4 . 1/2 . 3/4 . 1
-- Log: ( )A Bb( )A B( )
-- Code: * * * * *
delay Total / 8;
Check (Test, "()ABb()AB()", Get (Log));
exception
when Error : others => Test.Report_Exception (Error);
end Event_List_Fusion;
procedure Insert_While_Busy (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Insert entry while callback is running");
Total : constant Duration := 1.0;
Log : aliased Bounded_String (256);
begin
declare
Long, Short : Cron_Entry;
begin
Long.Set
(Total / 8,
Long_Callback'
(Backend => Log'Access,
Open => '(',
Close => ')',
Wait => Total / 5));
delay Total / 8 + Total / 16;
Short.Set
(Total / 8,
Test_Callback'(Backend => Log'Access, Symbol => '.'));
delay Total / 2 + Total / 8;
end;
-- Timeline: 0 . 1/8 . 1/4 . 3/8 . 1/2 . 5/8 . 3/4 . 7/8 . 1
-- Set: L S
-- Finalize: *
-- Ticks: L L S L S L S L S L
-- Run: <----L---->S <----L---->S <----L---->
delay Total / 8;
Check (Test, "().().()", Get (Log));
exception
when Error : others => Test.Report_Exception (Error);
end Insert_While_Busy;
procedure Time_Collision (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Simultaneous activation of events");
Total : constant Duration := 0.01;
Tick : constant Duration := Total / 4;
Log : aliased Bounded_String (256);
begin
declare
use type Ada.Calendar.Time;
Common : constant Periodic_Time := (Ada.Calendar.Clock + Tick, Tick);
First, Second, Third : Cron_Entry;
begin
First.Set
(Common, Test_Callback'(Backend => Log'Access, Symbol => '1'));
Second.Set
(Common, Test_Callback'(Backend => Log'Access, Symbol => '2'));
Third.Set
((Origin => Common.Origin, Period => 2 * Common.Period),
Test_Callback'(Backend => Log'Access, Symbol => '3'));
delay Total - Tick / 2;
end;
Check (Test, "12312123", Get (Log));
exception
when Error : others => Test.Report_Exception (Error);
end Time_Collision;
end Natools.Cron.Tests;
|
fix argument order in calls to Check
|
cron-tests: fix argument order in calls to Check
|
Ada
|
isc
|
faelys/natools
|
9a764b1da2eba6ca899569524abf308930eedd6d
|
tools/druss-commands-get.ads
|
tools/druss-commands-get.ads
|
-----------------------------------------------------------------------
-- druss-commands-get -- Raw JSON API Get command
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Druss.Commands.Get is
type Command_Type is new Druss.Commands.Drivers.Command_Type with null record;
-- Execute the GET API operation and print the raw JSON result.
procedure Execute_Operation (Command : in Command_Type;
Operation : in String;
Context : in out Context_Type);
-- Execute a GET operation on the Bbox API and return the raw JSON result.
overriding
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type);
end Druss.Commands.Get;
|
-----------------------------------------------------------------------
-- druss-commands-get -- Raw JSON API Get command
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Druss.Commands.Get is
type Command_Type is new Druss.Commands.Drivers.Command_Type with null record;
-- Execute a GET operation on the Bbox API and return the raw JSON result.
overriding
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type);
end Druss.Commands.Get;
|
Remove Execute_Operation procedure
|
Remove Execute_Operation procedure
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
2dd9034e9140c08755f24a539e17506c29b240b4
|
awa/plugins/awa-storages/src/awa-storages-beans.adb
|
awa/plugins/awa-storages/src/awa-storages-beans.adb
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Helpers.Requests;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
package body AWA.Storages.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Upload_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "folderId" then
return ADO.Objects.To_Object (From.Get_Folder.Get_Key);
end if;
return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Upload_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
Folder : Models.Storage_Folder_Ref;
begin
if Name = "folderId" then
Manager.Load_Folder (Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
From.Set_Folder (Folder);
end if;
end Set_Value;
-- ------------------------------
-- Save the uploaded file in the storage service.
-- ------------------------------
procedure Save_Part (Bean : in out Upload_Bean;
Part : in ASF.Parts.Part'Class) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Bean.Set_Name (Part.Get_Name);
Bean.Set_Mime_Type (Part.Get_Content_Type);
Bean.Set_File_Size (Part.Get_Size);
Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE);
end Save_Part;
-- ------------------------------
-- Upload the file.
-- ------------------------------
procedure Upload (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Upload;
-- ------------------------------
-- Delete the file.
-- @method
-- ------------------------------
procedure Delete (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Delete (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Delete;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if ADO.Objects.Is_Null (From) then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Save_Folder (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Save;
overriding
function Get_Value (List : in Storage_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return Models.Storage_Info_List_Bean (List).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Create the Folder_List_Bean bean instance.
-- ------------------------------
function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Folder_List_Bean;
-- ------------------------------
-- Create the Storage_List_Bean bean instance.
-- ------------------------------
function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Storage_List_Bean_Access := new Storage_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
Folder_Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter (FOLDER_ID_PARAMETER);
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
if Folder_Id = ADO.NO_IDENTIFIER then
Query.Bind_Null_Param ("folder_id");
else
Query.Bind_Param ("folder_id", Folder_Id);
end if;
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Storage_List_Bean;
end AWA.Storages.Beans;
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Helpers.Requests;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
package body AWA.Storages.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Upload_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "folderId" then
return ADO.Objects.To_Object (From.Get_Folder.Get_Key);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Upload_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
Folder : Models.Storage_Folder_Ref;
begin
if Name = "folderId" then
Manager.Load_Folder (Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
From.Set_Folder (Folder);
elsif Name = "id" then
Manager.Load_Storage (From, ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
end if;
end Set_Value;
-- ------------------------------
-- Save the uploaded file in the storage service.
-- ------------------------------
procedure Save_Part (Bean : in out Upload_Bean;
Part : in ASF.Parts.Part'Class) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Bean.Set_Name (Part.Get_Name);
Bean.Set_Mime_Type (Part.Get_Content_Type);
Bean.Set_File_Size (Part.Get_Size);
Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE);
end Save_Part;
-- ------------------------------
-- Upload the file.
-- ------------------------------
procedure Upload (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Upload;
-- ------------------------------
-- Delete the file.
-- @method
-- ------------------------------
procedure Delete (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Delete (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Delete;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if ADO.Objects.Is_Null (From) then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Save_Folder (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Save;
overriding
function Get_Value (List : in Storage_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return Models.Storage_Info_List_Bean (List).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Create the Folder_List_Bean bean instance.
-- ------------------------------
function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Folder_List_Bean;
-- ------------------------------
-- Create the Storage_List_Bean bean instance.
-- ------------------------------
function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Storage_List_Bean_Access := new Storage_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
Folder_Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter (FOLDER_ID_PARAMETER);
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
if Folder_Id = ADO.NO_IDENTIFIER then
Query.Bind_Null_Param ("folder_id");
else
Query.Bind_Param ("folder_id", Folder_Id);
end if;
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Storage_List_Bean;
end AWA.Storages.Beans;
|
Load the storage object
|
Load the storage object
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ff5c41e2ffbdbb46fa5e7eb8fb6392bcac9e02dc
|
src/security-openid.ads
|
src/security-openid.ads
|
-----------------------------------------------------------------------
-- security-openid -- Open ID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
with Security.Permissions;
-- == OpenID ==
-- The <b>Security.Openid</b> package implements an authentication framework based
-- on OpenID 2.0.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- The authentication process is the following:
--
-- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the
-- OpenID return callback CB.
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
-- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication
-- URL for the association.
-- * The application should redirected the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- There are basically two steps that an application must implement.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- == Step 1: creating the authentication URL ==
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenId manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>.
--
-- Mgr : Openid.Manager;
-- OP : Openid.End_Point;
-- Assoc : constant Association_Access := new Association;
--
-- The
--
-- Server.Initialize (Mgr);
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- == Step 2: verify the authentication in the callback URL ==
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Mgr : Openid.Manager;
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Auth : Openid.Authentication;
-- Params : Auth_Params;
--
-- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Server.Initialize (Mgr);
-- Mgr.Verify (Assoc.all, Params, Auth);
-- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure.
--
--
--
package Security.Openid is
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- OpenID provider
-- ------------------------------
-- The <b>End_Point</b> represents the OpenID provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The OpenID association contains the shared secret between the relying party
-- and the OpenID provider. The association can be cached and reused to authenticate
-- different users using the same OpenID provider. The association also has an
-- expiration date.
type Association is private;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- OpenID provider
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- OpenID Default principal
-- ------------------------------
type Principal is new Security.Permissions.Principal with private;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Permissions.Role_Type) return Boolean;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is tagged limited private;
-- Initialize the OpenID realm.
procedure Initialize (Realm : in out Manager;
Name : in String;
Return_To : in String);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
procedure Discover_XRDS (Realm : in out Manager;
URI : in String;
Result : out End_Point);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
use Ada.Strings.Unbounded;
type Association is record
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager is new Ada.Finalization.Limited_Controlled with record
Realm : Unbounded_String;
Return_To : Unbounded_String;
end record;
type Principal is new Security.Permissions.Principal with record
Auth : Authentication;
end record;
end Security.Openid;
|
-----------------------------------------------------------------------
-- security-openid -- Open ID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- with Security.Permissions;
-- == OpenID ==
-- The <b>Security.Openid</b> package implements an authentication framework based
-- on OpenID 2.0.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- The authentication process is the following:
--
-- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the
-- OpenID return callback CB.
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
-- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication
-- URL for the association.
-- * The application should redirected the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- There are basically two steps that an application must implement.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- == Discovery: creating the authentication URL ==
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenId manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>.
--
-- Mgr : Openid.Manager;
-- OP : Openid.End_Point;
-- Assoc : constant Association_Access := new Association;
--
-- The
--
-- Server.Initialize (Mgr);
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- == Verify: acknowledge the authentication in the callback URL ==
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Mgr : Openid.Manager;
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Auth : Openid.Authentication;
-- Params : Auth_Params;
--
-- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Server.Initialize (Mgr);
-- Mgr.Verify (Assoc.all, Params, Auth);
-- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure.
--
--
--
package Security.Openid is
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- OpenID provider
-- ------------------------------
-- The <b>End_Point</b> represents the OpenID provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The OpenID association contains the shared secret between the relying party
-- and the OpenID provider. The association can be cached and reused to authenticate
-- different users using the same OpenID provider. The association also has an
-- expiration date.
type Association is private;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- OpenID provider
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- OpenID Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
-- function Has_Role (User : in Principal;
-- Role : in Permissions.Role_Type) return Boolean;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is tagged limited private;
-- Initialize the OpenID realm.
procedure Initialize (Realm : in out Manager;
Name : in String;
Return_To : in String);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
procedure Discover_XRDS (Realm : in out Manager;
URI : in String;
Result : out End_Point);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
use Ada.Strings.Unbounded;
type Association is record
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager is new Ada.Finalization.Limited_Controlled with record
Realm : Unbounded_String;
Return_To : Unbounded_String;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
end Security.Openid;
|
Use the Principal defined in the Security package Add some documentation
|
Use the Principal defined in the Security package
Add some documentation
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
fc1a25c919e930edbc659f8ec0293193f945b18e
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Users.Models;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with Ada.Calendar;
with ADO.Sessions;
with ADO.Objects;
with ADO.SQL;
with Util.Log.Loggers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Setup the resource bundles.
App.Register ("wikiMsg", "wikis");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Admin_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Page_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Page_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_View_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_View_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Version_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Version_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Set_Create_Date (Ada.Calendar.Clock);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- Load the wiki space.
-- ------------------------------
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- Create the wiki page into the wiki space.
-- ------------------------------
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Page.Set_Is_Public (Into.Get_Is_Public);
Page.Set_Wiki (Into);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_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
-- Check that the user has the update wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
-- ------------------------------
-- Load the wiki page and its content.
-- ------------------------------
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Id);
Page.Load (DB, Id, Found);
Tags.Load_Tags (DB, Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- Load the wiki page and its content from the wiki space Id and the page name.
-- ------------------------------
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
Query : ADO.SQL.Query;
begin
Query.Bind_Param (1, Wiki);
Query.Bind_Param (2, Name);
Query.Set_Filter ("o.wiki_id = ? AND o.name = ?");
Page.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Page.Get_Id);
Tags.Load_Tags (DB, Page.Get_Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- Create a new wiki content for the wiki page.
-- ------------------------------
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
begin
-- Check that the user has the update wiki content permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Content;
-- ------------------------------
-- Save a new wiki content for the wiki page.
-- ------------------------------
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
begin
Ctx.Start;
Page.Set_Last_Version (Page.Get_Last_Version + 1);
if not Page.Is_Inserted then
Page.Save (DB);
end if;
Content.Set_Page (Page);
Content.Set_Create_Date (Ada.Calendar.Clock);
Content.Set_Author (User);
Content.Set_Page_Version (Page.Get_Last_Version);
Content.Save (DB);
Page.Set_Content (Content);
Page.Save (DB);
Ctx.Commit;
end Save_Wiki_Content;
end AWA.Wikis.Modules;
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Users.Models;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with Ada.Calendar;
with ADO.Sessions;
with ADO.Objects;
with ADO.SQL;
with Util.Log.Loggers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Setup the resource bundles.
App.Register ("wikiMsg", "wikis");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Admin_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Page_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Page_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_View_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_View_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Version_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Version_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Set_Create_Date (Ada.Calendar.Clock);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- Load the wiki space.
-- ------------------------------
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- Create the wiki page into the wiki space.
-- ------------------------------
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Page.Set_Is_Public (Into.Get_Is_Public);
Page.Set_Wiki (Into);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_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
-- Check that the user has the update wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
-- ------------------------------
-- Load the wiki page and its content.
-- ------------------------------
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Id);
Page.Load (DB, Id, Found);
Tags.Load_Tags (DB, Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- Load the wiki page and its content from the wiki space Id and the page name.
-- ------------------------------
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
Query : ADO.SQL.Query;
begin
Query.Bind_Param (1, Wiki);
Query.Bind_Param (2, Name);
Query.Set_Filter ("o.wiki_id = ? AND o.name = ?");
Page.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Page.Get_Id);
Tags.Load_Tags (DB, Page.Get_Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- Create a new wiki content for the wiki page.
-- ------------------------------
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
begin
-- Check that the user has the update wiki content permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Content;
-- ------------------------------
-- Save a new wiki content for the wiki page.
-- ------------------------------
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Created : constant Boolean := not Page.Is_Inserted;
begin
Ctx.Start;
Page.Set_Last_Version (Page.Get_Last_Version + 1);
if Created then
Page.Save (DB);
end if;
Content.Set_Page (Page);
Content.Set_Create_Date (Ada.Calendar.Clock);
Content.Set_Author (User);
Content.Set_Page_Version (Page.Get_Last_Version);
Content.Save (DB);
Page.Set_Content (Content);
Page.Save (DB);
if Created then
Wiki_Lifecycle.Notify_Create (Model, Page);
else
Wiki_Lifecycle.Notify_Update (Model, Page);
end if;
Ctx.Commit;
end Save_Wiki_Content;
end AWA.Wikis.Modules;
|
Use the wiki lifecycle notification to notify listeners when a wiki page is created or updated
|
Use the wiki lifecycle notification to notify listeners when a wiki page is created or updated
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a1ab1942bd2455741b06722ba46d09b21f5c1cf8
|
matp/src/memory/mat-memory-targets.adb
|
matp/src/memory/mat-memory-targets.adb
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory 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 MAT.Memory.Probes;
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;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is
Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access
:= new MAT.Memory.Probes.Memory_Probe_Type;
begin
Memory_Probe.Data := Memory'Unrestricted_Access;
MAT.Memory.Probes.Register (Manager, Memory_Probe);
end Initialize;
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info) is
begin
Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-"
& MAT.Types.Hex_Image (Region.End_Addr) & "] - {0}", Region.Path);
Memory.Memory.Add_Region (Region);
end Add_Region;
-- ------------------------------
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map) is
begin
Memory.Memory.Find (From, To, Into);
end Find;
-- ------------------------------
-- 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 out 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;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat) is
begin
Memory.Memory.Stat_Information (Result);
end Stat_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
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Region : in Region_Info) is
begin
Regions.Insert (Region.Start_Addr, Region);
end Add_Region;
-- ------------------------------
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map) is
Iter : Region_Info_Cursor;
begin
Iter := Regions.Ceiling (From);
while Region_Info_Maps.Has_Element (Iter) loop
declare
Start : constant MAT.Types.Target_Addr := Region_Info_Maps.Key (Iter);
Region : Region_Info;
begin
exit when Start > To;
Region := Region_Info_Maps.Element (Iter);
if Region.End_Addr >= From then
if not Into.Contains (Start) then
Into.Insert (Start, Region);
end if;
end if;
Region_Info_Maps.Next (Iter);
end;
end loop;
end Find;
-- ------------------------------
-- 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
if Stats.Total_Free > Slot.Size then
Stats.Total_Free := Stats.Total_Free - Slot.Size;
else
Stats.Total_Free := 0;
end if;
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;
Stats.Malloc_Count := Stats.Malloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end if;
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 out 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;
Stats.Free_Count := Stats.Free_Count + 1;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
Slot.Size := Item.Size;
if Stats.Total_Alloc >= Item.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Item.Size;
else
Stats.Total_Alloc := 0;
end if;
Stats.Total_Free := Stats.Total_Free + Item.Size;
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Iter := Freed_Slots.Find (Addr);
if not Allocation_Maps.Has_Element (Iter) then
Freed_Slots.Insert (Addr, Item);
end if;
end if;
exception
when others =>
Log.Error ("Free {0} raised some exception", MAT.Types.Hex_Image (Addr));
raise;
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
if Stats.Total_Alloc >= Element.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Element.Size;
else
Stats.Total_Alloc := 0;
end if;
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;
Stats.Realloc_Count := Stats.Realloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
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;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Result : out Memory_Stat) is
begin
Result := Stats;
end Stat_Information;
end Memory_Allocator;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory 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 MAT.Memory.Probes;
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;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is
Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access
:= new MAT.Memory.Probes.Memory_Probe_Type;
begin
Memory_Probe.Data := Memory'Unrestricted_Access;
MAT.Memory.Probes.Register (Manager, Memory_Probe);
end Initialize;
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info) is
begin
Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-"
& MAT.Types.Hex_Image (Region.End_Addr) & "] - {0}", Region.Path);
Memory.Memory.Add_Region (Region);
end Add_Region;
-- ------------------------------
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map) is
begin
Memory.Memory.Find (From, To, Into);
end Find;
-- ------------------------------
-- 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 out 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;
Old_Size : out MAT.Types.Target_Size) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot, Old_Size);
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;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat) is
begin
Memory.Memory.Stat_Information (Result);
end Stat_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
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Region : in Region_Info) is
begin
Regions.Insert (Region.Start_Addr, Region);
end Add_Region;
-- ------------------------------
-- Find the memory region that intersect the given section described by <tt>From</tt>
-- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt>
-- map.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Into : in out MAT.Memory.Region_Info_Map) is
Iter : Region_Info_Cursor;
begin
Iter := Regions.Ceiling (From);
while Region_Info_Maps.Has_Element (Iter) loop
declare
Start : constant MAT.Types.Target_Addr := Region_Info_Maps.Key (Iter);
Region : Region_Info;
begin
exit when Start > To;
Region := Region_Info_Maps.Element (Iter);
if Region.End_Addr >= From then
if not Into.Contains (Start) then
Into.Insert (Start, Region);
end if;
end if;
Region_Info_Maps.Next (Iter);
end;
end loop;
end Find;
-- ------------------------------
-- 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
if Stats.Total_Free > Slot.Size then
Stats.Total_Free := Stats.Total_Free - Slot.Size;
else
Stats.Total_Free := 0;
end if;
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;
Stats.Malloc_Count := Stats.Malloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end if;
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 out 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;
Stats.Free_Count := Stats.Free_Count + 1;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
Slot.Size := Item.Size;
if Stats.Total_Alloc >= Item.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Item.Size;
else
Stats.Total_Alloc := 0;
end if;
Stats.Total_Free := Stats.Total_Free + Item.Size;
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Iter := Freed_Slots.Find (Addr);
if not Allocation_Maps.Has_Element (Iter) then
Freed_Slots.Insert (Addr, Item);
end if;
end if;
exception
when others =>
Log.Error ("Free {0} raised some exception", MAT.Types.Hex_Image (Addr));
raise;
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;
Old_Size : out MAT.Types.Target_Size) 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
if Stats.Total_Alloc >= Element.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Element.Size;
else
Stats.Total_Alloc := 0;
end if;
Old_Size := Element.Size;
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;
Old_Size := 0;
Stats.Realloc_Count := Stats.Realloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
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
Old_Size := Allocation_Maps.Element (Pos).Size;
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;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Result : out Memory_Stat) is
begin
Result := Stats;
end Stat_Information;
end Memory_Allocator;
end MAT.Memory.Targets;
|
Update Probe_Realloc to return the old_size of the memory slot before the realloc
|
Update Probe_Realloc to return the old_size of the memory slot before the realloc
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
cd3eccffa3390f8fd981454b48d39c302dad96fc
|
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 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
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.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
Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
declare
Link : constant String := AWA.Tests.Helpers.Extract_Link (To_String (Content), "Info");
begin
end;
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");
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;
|
Add tests to check the history and info page on a wiki page
|
Add tests to check the history and info page on a wiki page
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
d80a05b98b594c77b28fabb8611ffd50acd0204f
|
awa/src/awa-applications.adb
|
awa/src/awa-applications.adb
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with ADO.Drivers;
with EL.Contexts.Default;
with Util.Files;
with Util.Log.Loggers;
with ASF.Server;
with ASF.Servlets;
with AWA.Services.Contexts;
with AWA.Components.Factory;
with AWA.Applications.Factory;
with AWA.Applications.Configs;
with AWA.Helpers.Selectors;
with AWA.Permissions.Services;
package body AWA.Applications is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Applications");
-- ------------------------------
-- Initialize the application
-- ------------------------------
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
Ctx : AWA.Services.Contexts.Service_Context;
begin
Log.Info ("Initializing application");
Ctx.Set_Context (App'Unchecked_Access, null);
AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access);
ASF.Applications.Main.Application (App).Initialize (Conf, Factory);
-- Load the application configuration before any module.
Application'Class (App).Load_Configuration;
-- Register the application modules and load their configuration.
Application'Class (App).Initialize_Modules;
end Initialize;
-- ------------------------------
-- Initialize the application configuration properties. Properties defined in <b>Conf</b>
-- are expanded by using the EL expression resolver.
-- ------------------------------
overriding
procedure Initialize_Config (App : in out Application;
Conf : in out ASF.Applications.Config) is
begin
Log.Info ("Initializing configuration");
if Conf.Get ("app.modules.dir", "") = "" then
Conf.Set ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}");
end if;
if Conf.Get ("bundle.dir", "") = "" then
Conf.Set ("bundle.dir", "#{fn:composePath(app_search_dirs,'bundles')}");
end if;
if Conf.Get ("ado.queries.paths", "") = "" then
Conf.Set ("ado.queries.paths", "#{fn:composePath(app_search_dirs,'db')}");
end if;
ASF.Applications.Main.Application (App).Initialize_Config (Conf);
ADO.Drivers.Initialize (Conf);
App.DB_Factory.Create (Conf.Get ("database"));
App.Events.Initialize (App'Unchecked_Access);
AWA.Modules.Initialize (App.Modules, Conf);
App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean",
AWA.Helpers.Selectors.Create_Select_List_Bean'Access);
end Initialize_Config;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets");
ASF.Applications.Main.Application (App).Initialize_Servlets;
end Initialize_Servlets;
-- ------------------------------
-- 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) is
begin
Log.Info ("Initializing application filters");
ASF.Applications.Main.Application (App).Initialize_Filters;
end Initialize_Filters;
-- ------------------------------
-- 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) is
procedure Register_Functions is
new ASF.Applications.Main.Register_Functions (AWA.Permissions.Services.Set_Functions);
begin
Log.Info ("Initializing application components");
ASF.Applications.Main.Application (App).Initialize_Components;
App.Add_Components (AWA.Components.Factory.Definition);
Register_Functions (App);
end Initialize_Components;
-- ------------------------------
-- Read the application configuration file <b>awa.xml</b>. This is called after the servlets
-- and filters have been registered in the application but before the module registration.
-- ------------------------------
procedure Load_Configuration (App : in out Application) is
procedure Load_Config (File : in String;
Done : out Boolean);
Paths : constant String := App.Get_Config (P_Module_Dir.P);
Files : constant String := App.Get_Config (P_Config_File.P);
Ctx : aliased EL.Contexts.Default.Default_Context;
procedure Load_Config (File : in String;
Done : out Boolean) is
Path : constant String := Util.Files.Find_File_Path (File, Paths);
begin
Done := False;
AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Warn ("Application configuration file '{0}' does not exist", Path);
end Load_Config;
begin
Util.Files.Iterate_Path (Files, Load_Config'Access);
end Load_Configuration;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
procedure Initialize_Modules (App : in out Application) is
begin
null;
end Initialize_Modules;
-- ------------------------------
-- Start the application. This is called by the server container when the server is started.
-- ------------------------------
overriding
procedure Start (App : in out Application) is
begin
-- Start the event service.
App.Events.Start;
-- Start the application.
ASF.Applications.Main.Application (App).Start;
end Start;
-- ------------------------------
-- Register the module in the application
-- ------------------------------
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "") is
begin
App.Register (Module.all'Unchecked_Access, Name, URI);
end Register;
-- ------------------------------
-- Get the database connection for reading
-- ------------------------------
function Get_Session (App : Application)
return ADO.Sessions.Session is
begin
return App.DB_Factory.Get_Session;
end Get_Session;
-- ------------------------------
-- Get the database connection for writing
-- ------------------------------
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session is
begin
return App.DB_Factory.Get_Master_Session;
end Get_Master_Session;
-- ------------------------------
-- Find the module with the given name
-- ------------------------------
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access is
begin
return AWA.Modules.Find_By_Name (App.Modules, Name);
end Find_Module;
-- ------------------------------
-- Register the module in the application
-- ------------------------------
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "") is
begin
AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI);
end Register;
-- ------------------------------
-- Send the event in the application event queues.
-- ------------------------------
procedure Send_Event (App : in Application;
Event : in AWA.Events.Module_Event'Class) is
begin
App.Events.Send (Event);
end Send_Event;
-- ------------------------------
-- Execute the <tt>Process</tt> procedure with the event manager used by the application.
-- ------------------------------
procedure Do_Event_Manager (App : in out Application;
Process : access procedure
(Events : in out AWA.Events.Services.Event_Manager)) is
begin
Process (App.Events);
end Do_Event_Manager;
-- ------------------------------
-- Initialize the parser represented by <b>Parser</b> to recognize the configuration
-- that are specific to the plugins that have been registered so far.
-- ------------------------------
procedure Initialize_Parser (App : in out Application'Class;
Parser : in out Util.Serialize.IO.Parser'Class) is
procedure Process (Module : in out AWA.Modules.Module'Class);
procedure Process (Module : in out AWA.Modules.Module'Class) is
begin
Module.Initialize_Parser (Parser);
end Process;
begin
AWA.Modules.Iterate (App.Modules, Process'Access);
end Initialize_Parser;
-- ------------------------------
-- Get the current application from the servlet context or service context.
-- ------------------------------
function Current return Application_Access is
use type AWA.Services.Contexts.Service_Context_Access;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
begin
if Ctx /= null then
return Ctx.Get_Application;
end if;
-- If there is no service context, look in the servlet current context.
declare
use type ASF.Servlets.Servlet_Registry_Access;
Ctx : constant ASF.Servlets.Servlet_Registry_Access := ASF.Server.Current;
begin
if Ctx = null then
Log.Warn ("There is no service context");
return null;
end if;
if not (Ctx.all in AWA.Applications.Application'Class) then
Log.Warn ("The servlet context is not an application");
return null;
end if;
return AWA.Applications.Application'Class (Ctx.all)'Access;
end;
end Current;
end AWA.Applications;
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with ADO.Drivers;
with EL.Contexts.Default;
with Util.Files;
with Util.Log.Loggers;
with ASF.Server;
with ASF.Servlets;
with AWA.Services.Contexts;
with AWA.Components.Factory;
with AWA.Applications.Factory;
with AWA.Applications.Configs;
with AWA.Helpers.Selectors;
with AWA.Permissions.Services;
package body AWA.Applications is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Applications");
-- ------------------------------
-- Initialize the application
-- ------------------------------
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
Ctx : AWA.Services.Contexts.Service_Context;
begin
Log.Info ("Initializing application");
Ctx.Set_Context (App'Unchecked_Access, null);
AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access);
ASF.Applications.Main.Application (App).Initialize (Conf, Factory);
-- Load the application configuration before any module.
Application'Class (App).Load_Configuration (App.Get_Config (P_Config_File.P));
-- Register the application modules and load their configuration.
Application'Class (App).Initialize_Modules;
-- Load the plugin application configuration after the module are configured.
Application'Class (App).Load_Configuration (App.Get_Config (P_Plugin_Config_File.P));
end Initialize;
-- ------------------------------
-- Initialize the application configuration properties. Properties defined in <b>Conf</b>
-- are expanded by using the EL expression resolver.
-- ------------------------------
overriding
procedure Initialize_Config (App : in out Application;
Conf : in out ASF.Applications.Config) is
begin
Log.Info ("Initializing configuration");
if Conf.Get ("app.modules.dir", "") = "" then
Conf.Set ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}");
end if;
if Conf.Get ("bundle.dir", "") = "" then
Conf.Set ("bundle.dir", "#{fn:composePath(app_search_dirs,'bundles')}");
end if;
if Conf.Get ("ado.queries.paths", "") = "" then
Conf.Set ("ado.queries.paths", "#{fn:composePath(app_search_dirs,'db')}");
end if;
ASF.Applications.Main.Application (App).Initialize_Config (Conf);
ADO.Drivers.Initialize (Conf);
App.DB_Factory.Create (Conf.Get ("database"));
App.Events.Initialize (App'Unchecked_Access);
AWA.Modules.Initialize (App.Modules, Conf);
App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean",
AWA.Helpers.Selectors.Create_Select_List_Bean'Access);
end Initialize_Config;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets");
ASF.Applications.Main.Application (App).Initialize_Servlets;
end Initialize_Servlets;
-- ------------------------------
-- 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) is
begin
Log.Info ("Initializing application filters");
ASF.Applications.Main.Application (App).Initialize_Filters;
end Initialize_Filters;
-- ------------------------------
-- 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) is
procedure Register_Functions is
new ASF.Applications.Main.Register_Functions (AWA.Permissions.Services.Set_Functions);
begin
Log.Info ("Initializing application components");
ASF.Applications.Main.Application (App).Initialize_Components;
App.Add_Components (AWA.Components.Factory.Definition);
Register_Functions (App);
end Initialize_Components;
-- ------------------------------
-- Read the application configuration file <b>awa.xml</b>. This is called after the servlets
-- and filters have been registered in the application but before the module registration.
-- ------------------------------
procedure Load_Configuration (App : in out Application;
Files : in String) is
procedure Load_Config (File : in String;
Done : out Boolean);
Paths : constant String := App.Get_Config (P_Module_Dir.P);
Ctx : aliased EL.Contexts.Default.Default_Context;
procedure Load_Config (File : in String;
Done : out Boolean) is
Path : constant String := Util.Files.Find_File_Path (File, Paths);
begin
Done := False;
AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Warn ("Application configuration file '{0}' does not exist", Path);
end Load_Config;
begin
Util.Files.Iterate_Path (Files, Load_Config'Access);
end Load_Configuration;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
procedure Initialize_Modules (App : in out Application) is
begin
null;
end Initialize_Modules;
-- ------------------------------
-- Start the application. This is called by the server container when the server is started.
-- ------------------------------
overriding
procedure Start (App : in out Application) is
begin
-- Start the event service.
App.Events.Start;
-- Start the application.
ASF.Applications.Main.Application (App).Start;
end Start;
-- ------------------------------
-- Register the module in the application
-- ------------------------------
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "") is
begin
App.Register (Module.all'Unchecked_Access, Name, URI);
end Register;
-- ------------------------------
-- Get the database connection for reading
-- ------------------------------
function Get_Session (App : Application)
return ADO.Sessions.Session is
begin
return App.DB_Factory.Get_Session;
end Get_Session;
-- ------------------------------
-- Get the database connection for writing
-- ------------------------------
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session is
begin
return App.DB_Factory.Get_Master_Session;
end Get_Master_Session;
-- ------------------------------
-- Find the module with the given name
-- ------------------------------
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access is
begin
return AWA.Modules.Find_By_Name (App.Modules, Name);
end Find_Module;
-- ------------------------------
-- Register the module in the application
-- ------------------------------
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "") is
begin
AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI);
end Register;
-- ------------------------------
-- Send the event in the application event queues.
-- ------------------------------
procedure Send_Event (App : in Application;
Event : in AWA.Events.Module_Event'Class) is
begin
App.Events.Send (Event);
end Send_Event;
-- ------------------------------
-- Execute the <tt>Process</tt> procedure with the event manager used by the application.
-- ------------------------------
procedure Do_Event_Manager (App : in out Application;
Process : access procedure
(Events : in out AWA.Events.Services.Event_Manager)) is
begin
Process (App.Events);
end Do_Event_Manager;
-- ------------------------------
-- Initialize the parser represented by <b>Parser</b> to recognize the configuration
-- that are specific to the plugins that have been registered so far.
-- ------------------------------
procedure Initialize_Parser (App : in out Application'Class;
Parser : in out Util.Serialize.IO.Parser'Class) is
procedure Process (Module : in out AWA.Modules.Module'Class);
procedure Process (Module : in out AWA.Modules.Module'Class) is
begin
Module.Initialize_Parser (Parser);
end Process;
begin
AWA.Modules.Iterate (App.Modules, Process'Access);
end Initialize_Parser;
-- ------------------------------
-- Get the current application from the servlet context or service context.
-- ------------------------------
function Current return Application_Access is
use type AWA.Services.Contexts.Service_Context_Access;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
begin
if Ctx /= null then
return Ctx.Get_Application;
end if;
-- If there is no service context, look in the servlet current context.
declare
use type ASF.Servlets.Servlet_Registry_Access;
Ctx : constant ASF.Servlets.Servlet_Registry_Access := ASF.Server.Current;
begin
if Ctx = null then
Log.Warn ("There is no service context");
return null;
end if;
if not (Ctx.all in AWA.Applications.Application'Class) then
Log.Warn ("The servlet context is not an application");
return null;
end if;
return AWA.Applications.Application'Class (Ctx.all)'Access;
end;
end Current;
end AWA.Applications;
|
Load the plugin configuration file after all the application modules have been registered
|
Load the plugin configuration file after all the application modules have been registered
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a91bffd2320c3eb347e37feb7cdb5e1659a97425
|
awa/src/awa-applications.ads
|
awa/src/awa-applications.ads
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- with AWA.Messages;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ADO.Sessions.Factory;
with AWA.Modules;
package AWA.Applications is
package P_Module_Dir is
new ASF.Applications.Main.Configs.Parameter ("app.module.dir", "./config");
package P_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config", "awa.xml");
-- Module manager
--
-- The <b>Module_Manager</b> represents the root of the logic manager
type Application is new ASF.Applications.Main.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class);
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
overriding
procedure Initialize_Servlets (App : in out Application);
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
overriding
procedure Initialize_Filters (App : in out Application);
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
overriding
procedure Initialize_Components (App : in out Application);
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
procedure Initialize_Modules (App : in out Application);
-- Register the module in the registry.
procedure Load_Configuration (App : in out Application);
-- Register the module in the application
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "");
-- Get the database connection for reading
function Get_Session (App : Application)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session;
-- Register the module in the application
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "");
-- Find the module with the given name
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access;
private
type Application is new ASF.Applications.Main.Application with record
DB_Factory : ADO.Sessions.Factory.Session_Factory;
Modules : aliased AWA.Modules.Module_Registry;
end record;
end AWA.Applications;
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- with AWA.Messages;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ADO.Sessions.Factory;
with AWA.Modules;
package AWA.Applications is
package P_Module_Dir is
new ASF.Applications.Main.Configs.Parameter ("app.modules.dir", "./config");
package P_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config", "awa.xml");
-- Module manager
--
-- The <b>Module_Manager</b> represents the root of the logic manager
type Application is new ASF.Applications.Main.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class);
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
overriding
procedure Initialize_Servlets (App : in out Application);
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
overriding
procedure Initialize_Filters (App : in out Application);
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
overriding
procedure Initialize_Components (App : in out Application);
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
procedure Initialize_Modules (App : in out Application);
-- Register the module in the registry.
procedure Load_Configuration (App : in out Application);
-- Register the module in the application
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "");
-- Get the database connection for reading
function Get_Session (App : Application)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session;
-- Register the module in the application
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "");
-- Find the module with the given name
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access;
private
type Application is new ASF.Applications.Main.Application with record
DB_Factory : ADO.Sessions.Factory.Session_Factory;
Modules : aliased AWA.Modules.Module_Registry;
end record;
end AWA.Applications;
|
Fix configuration property name
|
Fix configuration property name
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7a8f25f60ff8bfd8cd33939e49e0891bef424083
|
awa/plugins/awa-setup/src/awa-setup-applications.ads
|
awa/plugins/awa-setup/src/awa-setup-applications.ads
|
-----------------------------------------------------------------------
-- awa-setup -- Setup and installation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Requests;
with ASF.Responses;
with ASF.Server;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Methods;
with ADO.Drivers.Connections;
package AWA.Setup.Applications is
-- The <b>Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Redirect_Servlet is new ASF.Servlets.Servlet with null record;
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- The configuration state starts in the <tt>CONFIGURING</tt> state and moves to the
-- <tt>STARTING</tt> state after the application is configured and it is started.
-- Once the application is initialized and registered in the server container, the
-- state is changed to <tt>READY</tt>.
type Configure_State is (CONFIGURING, STARTING, READY);
-- Maintains the state of the configuration between the main task and the http configuration
-- requests.
protected type State is
-- Wait until the configuration is finished.
entry Wait_Configuring;
-- Wait until the server application is initialized and ready.
entry Wait_Ready;
-- Set the configuration state.
procedure Set (V : in Configure_State);
private
Value : Configure_State := CONFIGURING;
end State;
type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Redirect : aliased Redirect_Servlet;
Config : ASF.Applications.Config;
Changed : ASF.Applications.Config;
Factory : ASF.Applications.Main.Application_Factory;
Path : Ada.Strings.Unbounded.Unbounded_String;
Database : ADO.Drivers.Connections.Configuration;
Driver : Util.Beans.Objects.Object;
Result : Util.Beans.Objects.Object;
Root_User : Util.Beans.Objects.Object;
Root_Passwd : Util.Beans.Objects.Object;
Db_Host : Util.Beans.Objects.Object;
Db_Port : Util.Beans.Objects.Object;
Has_Error : Boolean := False;
Status : State;
end record;
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the database connection string to be used by the application.
function Get_Database_URL (From : in Application) return String;
-- Get the command to configure the database.
function Get_Configure_Command (From : in Application) return String;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Validate the database configuration parameters.
procedure Validate (From : in out Application);
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup to start the application.
procedure Start (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup and wait for the application to be started.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class);
-- Configure the application by using the setup application, allowing the administrator to
-- setup the application database, define the application admin parameters. After the
-- configuration is done, register the application in the server container and start it.
generic
type Application_Type (<>) is new ASF.Servlets.Servlet_Registry with private;
type Application_Access is access all Application_Type'Class;
with procedure Initialize (App : in Application_Access;
Config : in ASF.Applications.Config);
procedure Configure (Server : in out ASF.Server.Container'Class;
App : in Application_Access;
Config : in String;
URI : in String);
end AWA.Setup.Applications;
|
-----------------------------------------------------------------------
-- awa-setup-applications -- Setup and installation
-- 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 ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Requests;
with ASF.Responses;
with ASF.Server;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Beans.Methods;
with ADO.Drivers.Connections;
-- == Setup Procedure Instantiation==
-- The setup process is managed by the *Configure* generic procedure. The procedure must
-- be instantiated with the application class type and the application initialize procedure.
--
-- procedure Setup is
-- new AWA.Setup.Applications.Configure (MyApp.Application'Class,
-- MyApp.Application_Access,
-- MyApp.Initialize);
--
-- == Setup Operation ==
-- The *Setup* instantiated operation must then be called with the web container.
-- The web container is started first and the *Setup* procedure gets as parameter the
-- web container, the application instance to configure, the application name and
-- the application context path.
--
-- Setup (WS, App, "atlas", MyApp.CONTEXT_PATH)
--
-- The operation will install the setup application to handle the setup actions. Through
-- the setup actions, the installer will be able to:
--
-- * Configure the database (MySQL or SQLite),
-- * Configure the Google+ and Facebook OAuth authentication keys,
-- * Configure the application name,
-- * Configure the mail parameters to be able to send email.
--
-- After the setup and configure is finished, the file <tt>.initialized</tt> is created in
-- the application directory to indicate the application is configured. The next time the
-- *Setup* operation is called, the installation process will be skipped.
--
-- To run again the installation, remove manually the <tt>.initialized</tt> file.
package AWA.Setup.Applications is
-- The <b>Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Redirect_Servlet is new ASF.Servlets.Servlet with null record;
overriding
procedure Do_Get (Server : in Redirect_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- The configuration state starts in the <tt>CONFIGURING</tt> state and moves to the
-- <tt>STARTING</tt> state after the application is configured and it is started.
-- Once the application is initialized and registered in the server container, the
-- state is changed to <tt>READY</tt>.
type Configure_State is (CONFIGURING, STARTING, READY);
-- Maintains the state of the configuration between the main task and the http configuration
-- requests.
protected type State is
-- Wait until the configuration is finished.
entry Wait_Configuring;
-- Wait until the server application is initialized and ready.
entry Wait_Ready;
-- Set the configuration state.
procedure Set (V : in Configure_State);
private
Value : Configure_State := CONFIGURING;
end State;
type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Redirect : aliased Redirect_Servlet;
Config : ASF.Applications.Config;
Changed : ASF.Applications.Config;
Factory : ASF.Applications.Main.Application_Factory;
Path : Ada.Strings.Unbounded.Unbounded_String;
Database : ADO.Drivers.Connections.Configuration;
Driver : Util.Beans.Objects.Object;
Result : Util.Beans.Objects.Object;
Root_User : Util.Beans.Objects.Object;
Root_Passwd : Util.Beans.Objects.Object;
Db_Host : Util.Beans.Objects.Object;
Db_Port : Util.Beans.Objects.Object;
Has_Error : Boolean := False;
Status : State;
end record;
-- Get the value identified by the name.
function Get_Value (From : in Application;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
procedure Set_Value (From : in out Application;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the database connection string to be used by the application.
function Get_Database_URL (From : in Application) return String;
-- Get the command to configure the database.
function Get_Configure_Command (From : in Application) return String;
-- Configure the database.
procedure Configure_Database (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Validate the database configuration parameters.
procedure Validate (From : in out Application);
-- Save the configuration.
procedure Save (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup to start the application.
procedure Start (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Finish the setup and wait for the application to be started.
procedure Finish (From : in out Application;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Application)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Enter in the application setup
procedure Setup (App : in out Application;
Config : in String;
Server : in out ASF.Server.Container'Class);
-- Configure the application by using the setup application, allowing the administrator to
-- setup the application database, define the application admin parameters. After the
-- configuration is done, register the application in the server container and start it.
generic
type Application_Type (<>) is new ASF.Servlets.Servlet_Registry with private;
type Application_Access is access all Application_Type'Class;
with procedure Initialize (App : in Application_Access;
Config : in ASF.Applications.Config);
procedure Configure (Server : in out ASF.Server.Container'Class;
App : in Application_Access;
Config : in String;
URI : in String);
end AWA.Setup.Applications;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
95d5d9610e9e22233675ce40ffe5b16531fb792f
|
tests/natools-s_expressions-cache_tests.adb
|
tests/natools-s_expressions-cache_tests.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with System.Storage_Pools;
with GNAT.Debug_Pools;
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Caches;
with Natools.S_Expressions.Generic_Caches;
with Natools.S_Expressions.Printers;
with Natools.S_Expressions.Test_Tools;
package body Natools.S_Expressions.Cache_Tests is
Pool : GNAT.Debug_Pools.Debug_Pool;
package Debug_Caches is new Generic_Caches
(System.Storage_Pools.Root_Storage_Pool'Class (Pool),
System.Storage_Pools.Root_Storage_Pool'Class (Pool),
System.Storage_Pools.Root_Storage_Pool'Class (Pool));
procedure Inject_Test (Printer : in out Printers.Printer'Class);
-- Inject test S-expression into Pr
function Canonical_Test return Atom;
-- Return canonical encoding of test S-expression above
------------------------
-- Helper Subprograms --
------------------------
function Canonical_Test return Atom is
begin
return To_Atom ("5:begin(()(4:head4:tail))3:end");
end Canonical_Test;
procedure Inject_Test (Printer : in out Printers.Printer'Class) is
begin
Printer.Append_Atom (To_Atom ("begin"));
Printer.Open_List;
Printer.Open_List;
Printer.Close_List;
Printer.Open_List;
Printer.Append_Atom (To_Atom ("head"));
Printer.Append_Atom (To_Atom ("tail"));
Printer.Close_List;
Printer.Close_List;
Printer.Append_Atom (To_Atom ("end"));
end Inject_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Default_Instantiation (Report);
Debug_Instantiation (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Debug_Instantiation (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Debug instantiation");
Buffer : Atom_Buffers.Atom_Buffer;
procedure Put (S : in String);
procedure Put_Line (S : in String);
procedure Flush;
procedure Info_Pool;
procedure Put (S : in String) is
begin
Buffer.Append (To_Atom (S));
end Put;
procedure Put_Line (S : in String) is
begin
Test.Info (To_String (Buffer.Data) & S);
Buffer.Soft_Reset;
end Put_Line;
procedure Flush is
begin
if Buffer.Length > 0 then
Test.Info (To_String (Buffer.Data));
end if;
Buffer.Hard_Reset;
end Flush;
procedure Info_Pool is
procedure Print_Info is new GNAT.Debug_Pools.Print_Info;
begin
Print_Info (Pool);
Flush;
end Info_Pool;
begin
declare
Cache : Debug_Caches.Reference;
begin
Inject_Test (Cache);
declare
First : Debug_Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (First, Pr);
Output.Check_Stream (Test);
end;
declare
Second : Debug_Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (Second, Pr);
Output.Check_Stream (Test);
end;
end;
Info_Pool;
exception
when Error : others => Test.Report_Exception (Error);
end Debug_Instantiation;
procedure Default_Instantiation (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Default instantiation");
begin
declare
Cache : Caches.Reference;
begin
Inject_Test (Cache);
declare
First : Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (First, Pr);
Output.Check_Stream (Test);
end;
declare
Second : Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (Second, Pr);
Output.Check_Stream (Test);
end;
end;
exception
when Error : others => Test.Report_Exception (Error);
end Default_Instantiation;
end Natools.S_Expressions.Cache_Tests;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with System.Storage_Pools;
with GNAT.Debug_Pools;
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Caches;
with Natools.S_Expressions.Generic_Caches;
with Natools.S_Expressions.Printers;
with Natools.S_Expressions.Test_Tools;
package body Natools.S_Expressions.Cache_Tests is
Pool : GNAT.Debug_Pools.Debug_Pool;
package Debug_Caches is new Generic_Caches
(System.Storage_Pools.Root_Storage_Pool'Class (Pool),
System.Storage_Pools.Root_Storage_Pool'Class (Pool),
System.Storage_Pools.Root_Storage_Pool'Class (Pool));
procedure Inject_Test (Printer : in out Printers.Printer'Class);
-- Inject test S-expression into Pr
function Canonical_Test return Atom;
-- Return canonical encoding of test S-expression above
------------------------
-- Helper Subprograms --
------------------------
function Canonical_Test return Atom is
begin
return To_Atom ("5:begin(()(4:head4:tail))3:end");
end Canonical_Test;
procedure Inject_Test (Printer : in out Printers.Printer'Class) is
begin
Printer.Append_Atom (To_Atom ("begin"));
Printer.Open_List;
Printer.Open_List;
Printer.Close_List;
Printer.Open_List;
Printer.Append_Atom (To_Atom ("head"));
Printer.Append_Atom (To_Atom ("tail"));
Printer.Close_List;
Printer.Close_List;
Printer.Append_Atom (To_Atom ("end"));
end Inject_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Default_Instantiation (Report);
Debug_Instantiation (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Debug_Instantiation (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Debug instantiation");
Buffer : Atom_Buffers.Atom_Buffer;
procedure Put (S : in String);
procedure Put_Line (S : in String);
procedure Flush;
procedure Info_Pool;
procedure Put (S : in String) is
begin
Buffer.Append (To_Atom (S));
end Put;
procedure Put_Line (S : in String) is
begin
Test.Info (To_String (Buffer.Data) & S);
Buffer.Soft_Reset;
end Put_Line;
procedure Flush is
begin
if Buffer.Length > 0 then
Test.Info (To_String (Buffer.Data));
end if;
Buffer.Hard_Reset;
end Flush;
procedure Info_Pool is
procedure Print_Info is new GNAT.Debug_Pools.Print_Info;
begin
Print_Info (Pool);
Flush;
end Info_Pool;
begin
declare
Cache, Deep, Shallow : Debug_Caches.Reference;
begin
Inject_Test (Cache);
declare
First : Debug_Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (First, Pr);
Output.Check_Stream (Test);
end;
Deep := Cache.Duplicate;
Shallow := Deep;
Deep.Append_Atom (To_Atom ("more"));
declare
Other : Debug_Caches.Cursor := Deep.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Other, Pr);
Output.Check_Stream (Test);
end;
declare
Second : Debug_Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (Second, Pr);
Output.Check_Stream (Test);
end;
declare
Second_Other : Debug_Caches.Cursor := Shallow.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Second_Other, Pr);
Output.Check_Stream (Test);
end;
end;
Info_Pool;
exception
when Error : others => Test.Report_Exception (Error);
end Debug_Instantiation;
procedure Default_Instantiation (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Default instantiation");
begin
declare
Cache, Deep, Shallow : Caches.Reference;
begin
Inject_Test (Cache);
declare
First : Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (First, Pr);
Output.Check_Stream (Test);
end;
Deep := Cache.Duplicate;
Shallow := Deep;
Deep.Append_Atom (To_Atom ("more"));
declare
Other : Caches.Cursor := Deep.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Other, Pr);
Output.Check_Stream (Test);
end;
declare
Second : Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (Second, Pr);
Output.Check_Stream (Test);
end;
declare
Second_Other : Caches.Cursor := Shallow.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Second_Other, Pr);
Output.Check_Stream (Test);
end;
end;
exception
when Error : others => Test.Report_Exception (Error);
end Default_Instantiation;
end Natools.S_Expressions.Cache_Tests;
|
add deep- and shallow-copy to existing tests
|
s_expressions-cache_tests: add deep- and shallow-copy to existing tests
|
Ada
|
isc
|
faelys/natools
|
7b4b6155889a30eadc950efffa0e3af3d62b973f
|
awa/plugins/awa-questions/regtests/awa-questions-services-tests.adb
|
awa/plugins/awa-questions/regtests/awa-questions-services-tests.adb
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for storage service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Security.Contexts;
with ASF.Contexts.Faces;
with ASF.Contexts.Faces.Mockup;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Questions.Modules;
with AWA.Questions.Beans;
with AWA.Votes.Beans;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Questions.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list",
Test_List_Questions'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean",
Test_Question_Vote'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)",
Test_Question_Vote'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Manager;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I append strings in Ada?");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do?");
T.Manager.Save_Question (Q);
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do? "
& "This is a stupid question for someone who reads this file. "
& "But I need some long text for the unit test.");
T.Manager.Save_Question (Q);
end Test_Create_Question;
-- ------------------------------
-- Test list of questions.
-- ------------------------------
procedure Test_List_Questions (T : in out Test) is
use AWA.Questions.Models;
use type Util.Beans.Basic.Readonly_Bean_Access;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Module : AWA.Questions.Modules.Question_Module_Access;
List : Util.Beans.Basic.Readonly_Bean_Access;
Bean : Util.Beans.Objects.Object;
Count : Natural;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Module := AWA.Questions.Modules.Get_Question_Module;
List := AWA.Questions.Beans.Create_Question_List_Bean (Module);
T.Assert (List /= null, "The Create_Question_List_Bean returned null");
Bean := Util.Beans.Objects.To_Object (List);
T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null");
Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count;
T.Assert (Count > 0, "The list of question is empty");
end Test_List_Questions;
-- ------------------------------
-- Do a vote on a question through the question vote bean.
-- ------------------------------
procedure Do_Vote (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
Vote : AWA.Votes.Beans.Vote_Bean_Access;
begin
Bean := Context.Get_Bean ("questionVote");
T.Assert (Bean /= null, "The questionVote bean was not created");
T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class,
"The questionVote is not a Vote_Bean");
Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access;
Vote.Rating := 1;
Vote.Entity_Id := 1;
Vote.Vote_Up (Outcome);
end Do_Vote;
-- ------------------------------
-- Test anonymous user voting for a question.
-- ------------------------------
procedure Test_Question_Vote_Anonymous (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Do_Vote (T);
T.Fail ("Anonymous users should not be allowed to vote");
exception
when AWA.Permissions.NO_PERMISSION =>
null;
end Test_Question_Vote_Anonymous;
-- ------------------------------
-- Test voting for a question.
-- ------------------------------
procedure Test_Question_Vote (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Do_Vote (T);
end Test_Question_Vote;
end AWA.Questions.Services.Tests;
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for storage service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Security.Contexts;
with ASF.Contexts.Faces;
with ASF.Contexts.Faces.Mockup;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Questions.Modules;
with AWA.Questions.Beans;
with AWA.Votes.Beans;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Questions.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list",
Test_List_Questions'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean",
Test_Question_Vote'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)",
Test_Question_Vote'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Manager;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I append strings in Ada?");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do?");
T.Manager.Save_Question (Q);
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do? "
& "This is a stupid question for someone who reads this file. "
& "But I need some long text for the unit test.");
T.Manager.Save_Question (Q);
end Test_Create_Question;
-- ------------------------------
-- Test list of questions.
-- ------------------------------
procedure Test_List_Questions (T : in out Test) is
use AWA.Questions.Models;
use type Util.Beans.Basic.Readonly_Bean_Access;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Module : AWA.Questions.Modules.Question_Module_Access;
List : Util.Beans.Basic.Readonly_Bean_Access;
Bean : Util.Beans.Objects.Object;
Count : Natural;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Module := AWA.Questions.Modules.Get_Question_Module;
List := AWA.Questions.Beans.Create_Question_List_Bean (Module);
T.Assert (List /= null, "The Create_Question_List_Bean returned null");
Bean := Util.Beans.Objects.To_Object (List);
T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null");
Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count;
T.Assert (Count > 0, "The list of question is empty");
end Test_List_Questions;
-- ------------------------------
-- Do a vote on a question through the question vote bean.
-- ------------------------------
procedure Do_Vote (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
Vote : AWA.Votes.Beans.Vote_Bean_Access;
begin
Context.Set_Parameter ("id", "1");
Bean := Context.Get_Bean ("questionVote");
T.Assert (Bean /= null, "The questionVote bean was not created");
T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class,
"The questionVote is not a Vote_Bean");
Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access;
Vote.Rating := 1;
Vote.Entity_Id := 1;
Vote.Vote_Up (Outcome);
end Do_Vote;
-- ------------------------------
-- Test anonymous user voting for a question.
-- ------------------------------
procedure Test_Question_Vote_Anonymous (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Do_Vote (T);
T.Fail ("Anonymous users should not be allowed to vote");
exception
when AWA.Permissions.NO_PERMISSION =>
null;
end Test_Question_Vote_Anonymous;
-- ------------------------------
-- Test voting for a question.
-- ------------------------------
procedure Test_Question_Vote (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Do_Vote (T);
end Test_Question_Vote;
end AWA.Questions.Services.Tests;
|
Add the request parameter to simulate the ajax vote action
|
Add the request parameter to simulate the ajax vote action
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e66901677c209ee2254b1395d5d4fc32c9a8ba97
|
tests/natools-chunked_strings-tests-coverage.adb
|
tests/natools-chunked_strings-tests-coverage.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2013, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
procedure Natools.Chunked_Strings.Tests.Coverage
(Report : in out Natools.Tests.Reporter'Class)
is
package NT renames Natools.Tests;
procedure Report_Result
(Name : in String;
Reported : in out Boolean;
Result : in NT.Result := NT.Fail);
-- Report Result unless already reported
procedure Report_Result
(Name : in String;
Reported : in out Boolean;
Result : in NT.Result := NT.Fail) is
begin
if not Reported then
NT.Item (Report, Name, Result);
Reported := True;
end if;
end Report_Result;
begin
NT.Section (Report, "Extra tests for complete coverage");
declare
Name : constant String := "Index_Error raised in Element";
C : Character;
begin
C := Element (To_Chunked_String (Name), Name'Length + 1);
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "No exception has been raised.");
NT.Info (Report, "Return value: " & Character'Image (C));
exception
when Ada.Strings.Index_Error =>
NT.Item (Report, Name, NT.Success);
when Error : others =>
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Wrong exception "
& Ada.Exceptions.Exception_Name (Error)
& "has been raised.");
end;
declare
Name : constant String := "Index_Error raised in Replace_Element";
CS : Chunked_String := To_Chunked_String (Name);
begin
Replace_Element (CS, Name'Length + 1, '*');
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "No exception has been raised.");
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
exception
when Ada.Strings.Index_Error =>
NT.Item (Report, Name, NT.Success);
when Error : others =>
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Wrong exception "
& Ada.Exceptions.Exception_Name (Error)
& "has been raised.");
end;
declare
Name : constant String := "Function Duplicate";
S, T : Chunked_String;
begin
S := To_Chunked_String (Name);
T := Duplicate (S);
S.Unappend ("cate");
if To_String (T) /= Name then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report,
"Duplicate """ & To_String (T) & " does not match original");
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String
:= "Procedure Set_Chunked_String (Chunked_String, String)";
CS : Chunked_String;
begin
Set_Chunked_String (CS, Name);
if To_String (CS) /= Name then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Name & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Function Delete with empty range";
CS : Chunked_String;
begin
CS := Delete (To_Chunked_String (Name), 1, 0);
if To_String (CS) /= Name then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Name & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String
:= "Function Head with oversized Count and parameter override";
Pad : constant Character := ' ';
Shadow : constant String (1 .. Name'Length) := (others => Pad);
CS : Chunked_String;
begin
CS := Head (To_Chunked_String (Name), 2 * Name'Length, Pad, 10, 5);
if To_String (CS) /= Name & Shadow then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Name & Shadow & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String
:= "Function Tail with oversized Count and parameter override";
Pad : constant Character := ' ';
Shadow : constant String (1 .. Name'Length) := (others => Pad);
CS : Chunked_String;
begin
CS := Tail (To_Chunked_String (Name), 2 * Name'Length, Pad, 10, 5);
if To_String (CS) /= Shadow & Name then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Shadow & Name & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String
:= "Function ""*"" (Character) over multiple chunks";
CS : Chunked_String;
Count : constant Positive := 3 * Default_Chunk_Size + 2;
Template : constant Character := '$';
Ref : constant String := Ada.Strings.Fixed."*" (Count, Template);
begin
CS := Count * Template;
if To_String (CS) /= Ref then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Ref & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Function ""*"" (String) over multiple chunks";
CS : Chunked_String;
Count : constant Positive := Default_Chunk_Size + 2;
Template : constant String := "<>";
Ref : constant String := Ada.Strings.Fixed."*" (Count, Template);
begin
CS := Count * Template;
if To_String (CS) /= Ref then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Ref & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Procedure Chunked_Slice";
CS : Chunked_String;
Low : constant Positive := 11;
High : constant Positive := 17;
begin
Chunked_Slice (To_Chunked_String (Name), CS, Low, High);
if To_String (CS) /= Name (Low .. High) then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Name (Low .. High) & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Procedure Chunked_Slice (empty)";
CS : Chunked_String;
begin
Chunked_Slice (To_Chunked_String (Name), CS, 1, 0);
if To_String (CS) /= "" then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Function Index_Non_Blank with From";
CS : constant Chunked_String := To_Chunked_String (Name);
M, N : Natural;
begin
M := Index (CS, " ");
N := Index_Non_Blank (CS, M);
if N /= M + 1 then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value:" & Natural'Image (N));
NT.Info (Report, "Expected:" & Natural'Image (M + 1));
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Function Find_Token at string end";
CS : constant Chunked_String := To_Chunked_String ("--end");
First : Positive;
Last : Natural;
begin
Find_Token
(Source => CS,
Set => Maps.To_Set ("abcdefghijklmnopqrst"),
Test => Ada.Strings.Inside,
First => First,
Last => Last);
if First /= 3 or Last /= 5 then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report,
"Final interval:" & Natural'Image (First)
& " .." & Natural'Image (Last));
NT.Info (Report, "Expected: 3 .. 5");
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Comparisons of Chunked_Strings";
CS_Name : constant Chunked_String := To_Chunked_String (Name);
Prefix : constant Chunked_String := To_Chunked_String ("Comparisons");
Smaller : constant Chunked_String := To_Chunked_String ("Ca");
Reported : Boolean := False;
begin
if CS_Name <= Null_Chunked_String then
Report_Result (Name, Reported);
NT.Info (Report, "CS_Name <= Null_Chunked_String");
end if;
if Null_Chunked_String >= CS_Name then
Report_Result (Name, Reported);
NT.Info (Report, "Null_Chunked_String >= CS_Name");
end if;
if Prefix >= CS_Name then
Report_Result (Name, Reported);
NT.Info (Report, "Prefix >= CS_Name");
end if;
if CS_Name <= Prefix then
Report_Result (Name, Reported);
NT.Info (Report, "CS_Name <= Prefix");
end if;
if Smaller >= CS_Name then
Report_Result (Name, Reported);
NT.Info (Report, "Smaller >= CS_Name");
end if;
if CS_Name <= Smaller then
Report_Result (Name, Reported);
NT.Info (Report, "CS_Name <= Smaller");
end if;
Report_Result (Name, Reported, NT.Success);
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Procedure Index, backwards without match";
CS : constant Chunked_String := To_Chunked_String (Name);
N : Natural;
begin
N := Index
(Source => CS,
Set => Ada.Strings.Maps.To_Set ("."),
Test => Ada.Strings.Inside,
Going => Ada.Strings.Backward);
if N /= 0 then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Unexpected match at" & Natural'Image (N));
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Function Trim, one-sided";
Str : constant String := " word ";
Reported : Boolean := False;
begin
declare
CS : constant Chunked_String := To_Chunked_String (Str);
Left : constant String
:= Ada.Strings.Fixed.Trim (Str, Ada.Strings.Left);
Right : constant String
:= Ada.Strings.Fixed.Trim (Str, Ada.Strings.Right);
CS_Left : constant Chunked_String := Trim (CS, Ada.Strings.Left);
CS_Right : constant Chunked_String := Trim (CS, Ada.Strings.Right);
begin
if To_String (CS_Left) /= Left then
Report_Result (Name, Reported);
NT.Info (Report, "Found """ & To_String (CS_Left) & '"');
NT.Info (Report, "Expected """ & Left & '"');
end if;
if To_String (CS_Right) /= Right then
Report_Result (Name, Reported);
NT.Info (Report, "Found """ & To_String (CS_Right) & '"');
NT.Info (Report, "Expected """ & Right & '"');
end if;
end;
Report_Result (Name, Reported, NT.Success);
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
Natools.Tests.End_Section (Report);
end Natools.Chunked_Strings.Tests.Coverage;
|
------------------------------------------------------------------------------
-- Copyright (c) 2013, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
procedure Natools.Chunked_Strings.Tests.Coverage
(Report : in out Natools.Tests.Reporter'Class)
is
package NT renames Natools.Tests;
procedure Report_Result
(Name : in String;
Reported : in out Boolean;
Result : in NT.Result := NT.Fail);
-- Report Result unless already reported
procedure Report_Result
(Name : in String;
Reported : in out Boolean;
Result : in NT.Result := NT.Fail) is
begin
if not Reported then
NT.Item (Report, Name, Result);
Reported := True;
end if;
end Report_Result;
begin
NT.Section (Report, "Extra tests for complete coverage");
declare
Name : constant String := "Index_Error raised in Element";
C : Character;
begin
C := Element (To_Chunked_String (Name), Name'Length + 1);
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "No exception has been raised.");
NT.Info (Report, "Return value: " & Character'Image (C));
exception
when Ada.Strings.Index_Error =>
NT.Item (Report, Name, NT.Success);
when Error : others =>
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Wrong exception "
& Ada.Exceptions.Exception_Name (Error)
& "has been raised.");
end;
declare
Name : constant String := "Index_Error raised in Replace_Element";
CS : Chunked_String := To_Chunked_String (Name);
begin
Replace_Element (CS, Name'Length + 1, '*');
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "No exception has been raised.");
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
exception
when Ada.Strings.Index_Error =>
NT.Item (Report, Name, NT.Success);
when Error : others =>
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Wrong exception "
& Ada.Exceptions.Exception_Name (Error)
& "has been raised.");
end;
declare
Name : constant String := "Index_Error raised in function Slice";
CS : constant Chunked_String := To_Chunked_String (Name);
Str : String (1 .. 10);
begin
Str := Slice (CS, Name'Length, Name'Length + Str'Length - 1);
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "No exception has been raised.");
NT.Info (Report, "Final value: """ & Str & '"');
exception
when Ada.Strings.Index_Error =>
NT.Item (Report, Name, NT.Success);
when Error : others =>
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Wrong exception "
& Ada.Exceptions.Exception_Name (Error)
& "has been raised.");
end;
declare
Name : constant String := "Index_Error raised in function Chunked_Slice";
CS : constant Chunked_String := To_Chunked_String (Name);
Dest : Chunked_String;
begin
Dest := Chunked_Slice (CS, Name'Length, Name'Length + 10);
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "No exception has been raised.");
NT.Info (Report, "Final value: """ & To_String (Dest) & '"');
exception
when Ada.Strings.Index_Error =>
NT.Item (Report, Name, NT.Success);
when Error : others =>
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Wrong exception "
& Ada.Exceptions.Exception_Name (Error)
& "has been raised.");
end;
declare
Name : constant String
:= "Index_Error raised in procedure Chunked_Slice";
CS : constant Chunked_String := To_Chunked_String (Name);
Dest : Chunked_String;
begin
Chunked_Slice (CS, Dest, Name'Length + 10, Name'Length + 20);
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "No exception has been raised.");
NT.Info (Report, "Final value: """ & To_String (Dest) & '"');
exception
when Ada.Strings.Index_Error =>
NT.Item (Report, Name, NT.Success);
when Error : others =>
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Wrong exception "
& Ada.Exceptions.Exception_Name (Error)
& "has been raised.");
end;
declare
Name : constant String
:= "Index_Error raised in function Index (pattern)";
CS : constant Chunked_String := To_Chunked_String (Name);
N : Natural;
begin
N := Index (CS, ".", Name'Length + 1);
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "No exception has been raised.");
NT.Info (Report, "Final value:" & Integer'Image (N));
exception
when Ada.Strings.Index_Error =>
NT.Item (Report, Name, NT.Success);
when Error : others =>
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Wrong exception "
& Ada.Exceptions.Exception_Name (Error)
& "has been raised.");
end;
declare
Name : constant String := "Index_Error raised in function Index (set)";
CS : constant Chunked_String := To_Chunked_String (Name);
N : Natural;
begin
N := Index (CS, Maps.To_Set ("."), Name'Length + 1);
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "No exception has been raised.");
NT.Info (Report, "Final value:" & Integer'Image (N));
exception
when Ada.Strings.Index_Error =>
NT.Item (Report, Name, NT.Success);
when Error : others =>
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Wrong exception "
& Ada.Exceptions.Exception_Name (Error)
& "has been raised.");
end;
declare
Name : constant String := "Index_Error raised in function Replace_Slice";
CS : constant Chunked_String := To_Chunked_String (Name);
Dest : Chunked_String;
begin
Dest := Replace_Slice (CS, Name'Length + 10, 0, "Hello");
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "No exception has been raised.");
NT.Info (Report, "Final value: """ & To_String (Dest) & '"');
exception
when Ada.Strings.Index_Error =>
NT.Item (Report, Name, NT.Success);
when Error : others =>
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Wrong exception "
& Ada.Exceptions.Exception_Name (Error)
& "has been raised.");
end;
declare
Name : constant String := "Function Duplicate";
S, T : Chunked_String;
begin
S := To_Chunked_String (Name);
T := Duplicate (S);
S.Unappend ("cate");
if To_String (T) /= Name then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report,
"Duplicate """ & To_String (T) & " does not match original");
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String
:= "Procedure Set_Chunked_String (Chunked_String, String)";
CS : Chunked_String;
begin
Set_Chunked_String (CS, Name);
if To_String (CS) /= Name then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Name & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Function Delete with empty range";
CS : Chunked_String;
begin
CS := Delete (To_Chunked_String (Name), 1, 0);
if To_String (CS) /= Name then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Name & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String
:= "Function Head with oversized Count and parameter override";
Pad : constant Character := ' ';
Shadow : constant String (1 .. Name'Length) := (others => Pad);
CS : Chunked_String;
begin
CS := Head (To_Chunked_String (Name), 2 * Name'Length, Pad, 10, 5);
if To_String (CS) /= Name & Shadow then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Name & Shadow & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String
:= "Function Tail with oversized Count and parameter override";
Pad : constant Character := ' ';
Shadow : constant String (1 .. Name'Length) := (others => Pad);
CS : Chunked_String;
begin
CS := Tail (To_Chunked_String (Name), 2 * Name'Length, Pad, 10, 5);
if To_String (CS) /= Shadow & Name then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Shadow & Name & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String
:= "Function ""*"" (Character) over multiple chunks";
CS : Chunked_String;
Count : constant Positive := 3 * Default_Chunk_Size + 2;
Template : constant Character := '$';
Ref : constant String := Ada.Strings.Fixed."*" (Count, Template);
begin
CS := Count * Template;
if To_String (CS) /= Ref then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Ref & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Function ""*"" (String) over multiple chunks";
CS : Chunked_String;
Count : constant Positive := Default_Chunk_Size + 2;
Template : constant String := "<>";
Ref : constant String := Ada.Strings.Fixed."*" (Count, Template);
begin
CS := Count * Template;
if To_String (CS) /= Ref then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Ref & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Procedure Chunked_Slice";
CS : Chunked_String;
Low : constant Positive := 11;
High : constant Positive := 17;
begin
Chunked_Slice (To_Chunked_String (Name), CS, Low, High);
if To_String (CS) /= Name (Low .. High) then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
NT.Info (Report, "Expected: """ & Name (Low .. High) & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Procedure Chunked_Slice (empty)";
CS : Chunked_String;
begin
Chunked_Slice (To_Chunked_String (Name), CS, 1, 0);
if To_String (CS) /= "" then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value: """ & To_String (CS) & '"');
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Function Index_Non_Blank with From";
CS : constant Chunked_String := To_Chunked_String (Name);
M, N : Natural;
begin
M := Index (CS, " ");
N := Index_Non_Blank (CS, M);
if N /= M + 1 then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Final value:" & Natural'Image (N));
NT.Info (Report, "Expected:" & Natural'Image (M + 1));
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Function Find_Token at string end";
CS : constant Chunked_String := To_Chunked_String ("--end");
First : Positive;
Last : Natural;
begin
Find_Token
(Source => CS,
Set => Maps.To_Set ("abcdefghijklmnopqrst"),
Test => Ada.Strings.Inside,
First => First,
Last => Last);
if First /= 3 or Last /= 5 then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report,
"Final interval:" & Natural'Image (First)
& " .." & Natural'Image (Last));
NT.Info (Report, "Expected: 3 .. 5");
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Comparisons of Chunked_Strings";
CS_Name : constant Chunked_String := To_Chunked_String (Name);
Prefix : constant Chunked_String := To_Chunked_String ("Comparisons");
Smaller : constant Chunked_String := To_Chunked_String ("Ca");
Reported : Boolean := False;
begin
if CS_Name <= Null_Chunked_String then
Report_Result (Name, Reported);
NT.Info (Report, "CS_Name <= Null_Chunked_String");
end if;
if Null_Chunked_String >= CS_Name then
Report_Result (Name, Reported);
NT.Info (Report, "Null_Chunked_String >= CS_Name");
end if;
if Prefix >= CS_Name then
Report_Result (Name, Reported);
NT.Info (Report, "Prefix >= CS_Name");
end if;
if CS_Name <= Prefix then
Report_Result (Name, Reported);
NT.Info (Report, "CS_Name <= Prefix");
end if;
if Smaller >= CS_Name then
Report_Result (Name, Reported);
NT.Info (Report, "Smaller >= CS_Name");
end if;
if CS_Name <= Smaller then
Report_Result (Name, Reported);
NT.Info (Report, "CS_Name <= Smaller");
end if;
Report_Result (Name, Reported, NT.Success);
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Procedure Index, backwards without match";
CS : constant Chunked_String := To_Chunked_String (Name);
N : Natural;
begin
N := Index
(Source => CS,
Set => Ada.Strings.Maps.To_Set ("."),
Test => Ada.Strings.Inside,
Going => Ada.Strings.Backward);
if N /= 0 then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Unexpected match at" & Natural'Image (N));
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Function Trim, one-sided";
Str : constant String := " word ";
Reported : Boolean := False;
begin
declare
CS : constant Chunked_String := To_Chunked_String (Str);
Left : constant String
:= Ada.Strings.Fixed.Trim (Str, Ada.Strings.Left);
Right : constant String
:= Ada.Strings.Fixed.Trim (Str, Ada.Strings.Right);
CS_Left : constant Chunked_String := Trim (CS, Ada.Strings.Left);
CS_Right : constant Chunked_String := Trim (CS, Ada.Strings.Right);
begin
if To_String (CS_Left) /= Left then
Report_Result (Name, Reported);
NT.Info (Report, "Found """ & To_String (CS_Left) & '"');
NT.Info (Report, "Expected """ & Left & '"');
end if;
if To_String (CS_Right) /= Right then
Report_Result (Name, Reported);
NT.Info (Report, "Found """ & To_String (CS_Right) & '"');
NT.Info (Report, "Expected """ & Right & '"');
end if;
end;
Report_Result (Name, Reported, NT.Success);
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
Natools.Tests.End_Section (Report);
end Natools.Chunked_Strings.Tests.Coverage;
|
cover all Index_Error exceptions
|
chunked_strings-tests-coverage: cover all Index_Error exceptions
|
Ada
|
isc
|
faelys/natools
|
9986d22a58d6100b43d7b37c572a65aa791b37ee
|
tests/src/cbap_register_error_test.adb
|
tests/src/cbap_register_error_test.adb
|
pragma License (GPL);
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: GNU GPLv3 or any later as published by Free Software Foundation --
-- (see COPYING file) --
-- --
-- Copyright © 2015 darkestkhan --
------------------------------------------------------------------------------
-- This Program is Free Software: You can redistribute it and/or modify --
-- it under the terms of The GNU General Public License as published by --
-- the Free Software Foundation, either version 3 of the license, or --
-- (at Your option) any later version. --
-- --
-- This Program is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS for A PARTICULAR PURPOSE. See the --
-- GNU General Public License for more details. --
-- --
-- You should have received a copy of the GNU General Public License --
-- along with this program. If not, see <http://www.gnu.org/licenses/>. --
------------------------------------------------------------------------------
with Ada.Command_Line;
with CBAP;
procedure CBAP_Register_Error_Test is
---------------------------------------------------------------------------
procedure Cause_Error (Argument: in String)
is
begin
null;
end Cause_Error;
---------------------------------------------------------------------------
Got_Errors: Natural := 0;
---------------------------------------------------------------------------
begin
begin
CBAP.Register (Cause_Error'Unrestricted_Access, "letsroll=die");
exception
when CBAP.Incorrect_Called_On => Got_Errors := Got_Errors + 1;
end;
begin
CBAP.Register (Cause_Error'Unrestricted_Access, "help");
CBAP.Register (Cause_Error'Unrestricted_Access, "help");
exception
when Constraint_Error => Got_Errors := Got_Errors + 1;
end;
if Got_Errors /= 2 then
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
else
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
end if;
end CBAP_Register_Error_Test;
|
pragma License (GPL);
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: GNU GPLv3 or any later as published by Free Software Foundation --
-- (see COPYING file) --
-- --
-- Copyright © 2015 darkestkhan --
------------------------------------------------------------------------------
-- This Program is Free Software: You can redistribute it and/or modify --
-- it under the terms of The GNU General Public License as published by --
-- the Free Software Foundation, either version 3 of the license, or --
-- (at Your option) any later version. --
-- --
-- This Program is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS for A PARTICULAR PURPOSE. See the --
-- GNU General Public License for more details. --
-- --
-- You should have received a copy of the GNU General Public License --
-- along with this program. If not, see <http://www.gnu.org/licenses/>. --
------------------------------------------------------------------------------
with Ada.Command_Line;
with CBAP;
procedure CBAP_Register_Error_Test is
---------------------------------------------------------------------------
procedure Cause_Error (Argument: in String) is null;
---------------------------------------------------------------------------
Got_Errors: Natural := 0;
---------------------------------------------------------------------------
begin
begin
CBAP.Register (Cause_Error'Unrestricted_Access, "letsroll=die");
exception
when CBAP.Incorrect_Called_On => Got_Errors := Got_Errors + 1;
end;
begin
CBAP.Register (Cause_Error'Unrestricted_Access, "help");
CBAP.Register (Cause_Error'Unrestricted_Access, "help");
exception
when Constraint_Error => Got_Errors := Got_Errors + 1;
end;
if Got_Errors /= 2 then
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
else
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
end if;
end CBAP_Register_Error_Test;
|
Use null procedure declaration.
|
Use null procedure declaration.
Signed-off-by: darkestkhan <[email protected]>
|
Ada
|
isc
|
darkestkhan/cbap
|
43677b4a97a113c8c6639e391e73effe14a4250d
|
mat/src/gtk/mat-targets-gtkmat.ads
|
mat/src/gtk/mat-targets-gtkmat.ads
|
-----------------------------------------------------------------------
-- mat-targets-gtkmat - Gtk target management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Gtk.Widget;
with Gtkada.Builder;
with MAT.Consoles.Gtkmat;
package MAT.Targets.Gtkmat is
type Target_Type is new MAT.Targets.Target_Type with private;
type Target_Type_Access is access all Target_Type'Class;
-- Initialize the target instance.
overriding
procedure Initialize (Target : in out Target_Type);
-- Release the storage.
overriding
procedure Finalize (Target : in out Target_Type);
-- Initialize the widgets and create the Gtk gui.
procedure Initialize_Widget (Target : in out Target_Type;
Widget : out Gtk.Widget.Gtk_Widget);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
overriding
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
overriding
procedure Interactive (Target : in out Target_Type);
-- Set the UI label with the given value.
procedure Set_Label (Target : in Target_Type;
Name : in String;
Value : in String);
-- Refresh the information about the current process.
procedure Refresh_Process (Target : in out Target_Type);
private
task type Gtk_Loop is
entry Start (Target : in Target_Type_Access);
end Gtk_Loop;
type Target_Type is new MAT.Targets.Target_Type with record
Builder : Gtkada.Builder.Gtkada_Builder;
Gui_Task : Gtk_Loop;
Previous_Event_Counter : Integer := 0;
Gtk_Console : MAT.Consoles.Gtkmat.Console_Type_Access;
Main : Gtk.Widget.Gtk_Widget;
About : Gtk.Widget.Gtk_Widget;
Chooser : Gtk.Widget.Gtk_Widget;
end record;
end MAT.Targets.Gtkmat;
|
-----------------------------------------------------------------------
-- mat-targets-gtkmat - Gtk target management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Gtk.Widget;
with Gtkada.Builder;
with MAT.Events.Gtkmat;
with MAT.Consoles.Gtkmat;
package MAT.Targets.Gtkmat is
type Target_Type is new MAT.Targets.Target_Type with private;
type Target_Type_Access is access all Target_Type'Class;
-- Initialize the target instance.
overriding
procedure Initialize (Target : in out Target_Type);
-- Release the storage.
overriding
procedure Finalize (Target : in out Target_Type);
-- Initialize the widgets and create the Gtk gui.
procedure Initialize_Widget (Target : in out Target_Type;
Widget : out Gtk.Widget.Gtk_Widget);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
overriding
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
overriding
procedure Interactive (Target : in out Target_Type);
-- Set the UI label with the given value.
procedure Set_Label (Target : in Target_Type;
Name : in String;
Value : in String);
-- Refresh the information about the current process.
procedure Refresh_Process (Target : in out Target_Type);
private
task type Gtk_Loop is
entry Start (Target : in Target_Type_Access);
end Gtk_Loop;
type Target_Type is new MAT.Targets.Target_Type with record
Builder : Gtkada.Builder.Gtkada_Builder;
Gui_Task : Gtk_Loop;
Previous_Event_Counter : Integer := 0;
Gtk_Console : MAT.Consoles.Gtkmat.Console_Type_Access;
Main : Gtk.Widget.Gtk_Widget;
About : Gtk.Widget.Gtk_Widget;
Chooser : Gtk.Widget.Gtk_Widget;
Events : MAT.Events.Gtkmat.Event_Drawing_Type;
end record;
procedure Refresh_Events (Target : in out Target_Type);
end MAT.Targets.Gtkmat;
|
Declare the Refresh_Events procedure
|
Declare the Refresh_Events procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
677b857ac0f95b8744e91d61bfb18707026c8f77
|
regtests/util-properties-tests.adb
|
regtests/util-properties-tests.adb
|
-----------------------------------------------------------------------
-- util-properties-tests -- Tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 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 Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
T.Assert (Exists (Props, +("test")) = False,
"Invalid properties");
T.Assert (Props.Is_Empty, "Property manager should be empty");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
declare
V : constant String := Props.Get (+("test"));
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
declare
V : constant Unbounded_String := Props.Get (+("test"));
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
begin
V := Props.Get (+("missing"));
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted");
-- Check exception on Get returning a String.
begin
declare
S : constant String := Props.Get ("missing");
pragma Unreferenced (S);
begin
T.Fail ("Exception NO_PROPERTY was not raised");
end;
exception
when NO_PROPERTY =>
null;
end;
-- Check exception on Get returning a String.
begin
declare
S : constant String := Props.Get (+("missing"));
pragma Unreferenced (S);
begin
T.Fail ("Exception NO_PROPERTY was not raised");
end;
exception
when NO_PROPERTY =>
null;
end;
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
procedure Test_Load_Ini_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
V := Props.Get_Value ("mysqld");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
declare
P : Properties.Manager;
begin
P := Props.Get ("mysqld");
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
P := Props.Get ("mysqld_safe");
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
declare
P : Properties.Manager with Unreferenced;
begin
P := Props.Get ("bad");
T.Fail ("No exception raised for Get()");
exception
when NO_PROPERTY =>
null;
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf");
raise;
end Test_Load_Ini_Property;
procedure Test_Save_Properties (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties");
begin
declare
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
Props.Set ("New-Property", "Some-Value");
Props.Remove ("mysqld");
T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed");
Props.Save_Properties (Path);
end;
declare
Props : Properties.Manager;
V : Util.Properties.Value;
P : Properties.Manager;
begin
Props.Load_Properties (Path => Path);
T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)");
T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
end Test_Save_Properties;
procedure Test_Remove_Property (T : in out Test) is
Props : Properties.Manager;
begin
begin
Props.Remove ("missing");
T.Fail ("Remove should raise exception");
exception
when NO_PROPERTY =>
null;
end;
begin
Props.Remove (+("missing"));
T.Fail ("Remove should raise exception");
exception
when NO_PROPERTY =>
null;
end;
Props.Set ("a", "b");
T.Assert (Props.Exists ("a"), "Property not inserted");
Props.Remove ("a");
T.Assert (not Props.Exists ("a"), "Property not removed");
Props.Set ("a", +("b"));
T.Assert (Props.Exists ("a"), "Property not inserted");
Props.Remove (+("a"));
T.Assert (not Props.Exists ("a"), "Property not removed");
end Test_Remove_Property;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Remove",
Test_Remove_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)",
Test_Load_Ini_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties",
Test_Save_Properties'Access);
end Add_Tests;
end Util.Properties.Tests;
|
-----------------------------------------------------------------------
-- util-properties-tests -- Tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 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 Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
T.Assert (Exists (Props, +("test")) = False,
"Invalid properties");
T.Assert (Props.Is_Empty, "Property manager should be empty");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
declare
V : constant String := Props.Get (+("test"));
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
declare
V : constant Unbounded_String := Props.Get (+("test"));
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
begin
V := Props.Get (+("missing"));
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted");
-- Check exception on Get returning a String.
begin
declare
S : constant String := Props.Get ("missing");
pragma Unreferenced (S);
begin
T.Fail ("Exception NO_PROPERTY was not raised");
end;
exception
when NO_PROPERTY =>
null;
end;
-- Check exception on Get returning a String.
begin
declare
S : constant String := Props.Get (+("missing"));
pragma Unreferenced (S);
begin
T.Fail ("Exception NO_PROPERTY was not raised");
end;
exception
when NO_PROPERTY =>
null;
end;
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
procedure Test_Load_Ini_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
V := Props.Get_Value ("mysqld");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
declare
P : Properties.Manager;
begin
P := Props.Get ("mysqld");
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
P := Props.Get ("mysqld_safe");
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
declare
P : Properties.Manager with Unreferenced;
begin
P := Props.Get ("bad");
T.Fail ("No exception raised for Get()");
exception
when NO_PROPERTY =>
null;
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf");
raise;
end Test_Load_Ini_Property;
procedure Test_Save_Properties (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties");
begin
declare
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
Props.Set ("New-Property", "Some-Value");
Props.Remove ("mysqld");
T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed");
Props.Save_Properties (Path);
end;
declare
Props : Properties.Manager;
V : Util.Properties.Value;
P : Properties.Manager;
begin
Props.Load_Properties (Path => Path);
T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)");
T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
P := Util.Properties.To_Manager (V);
T.Fail ("No exception raised by To_Manager");
exception
when Util.Beans.Objects.Conversion_Error =>
null;
end;
end Test_Save_Properties;
procedure Test_Remove_Property (T : in out Test) is
Props : Properties.Manager;
begin
begin
Props.Remove ("missing");
T.Fail ("Remove should raise exception");
exception
when NO_PROPERTY =>
null;
end;
begin
Props.Remove (+("missing"));
T.Fail ("Remove should raise exception");
exception
when NO_PROPERTY =>
null;
end;
Props.Set ("a", "b");
T.Assert (Props.Exists ("a"), "Property not inserted");
Props.Remove ("a");
T.Assert (not Props.Exists ("a"), "Property not removed");
Props.Set ("a", +("b"));
T.Assert (Props.Exists ("a"), "Property not inserted");
Props.Remove (+("a"));
T.Assert (not Props.Exists ("a"), "Property not removed");
end Test_Remove_Property;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Remove",
Test_Remove_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)",
Test_Load_Ini_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties",
Test_Save_Properties'Access);
end Add_Tests;
end Util.Properties.Tests;
|
Add more test for To_Manager function
|
Add more test for To_Manager function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
dea2f519ef9c2655aa60c157b1eac06946d13f71
|
src/sys/streams/util-streams.ads
|
src/sys/streams/util-streams.ads
|
-----------------------------------------------------------------------
-- util-streams -- Stream utilities
-- Copyright (C) 2010, 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.Streams;
-- = Streams =
-- The `Util.Streams` package provides several types and operations to allow the
-- composition of input and output streams. Input streams can be chained together so that
-- they traverse the different stream objects when the data is read from them. Similarly,
-- output streams can be chained and the data that is written will traverse the different
-- streams from the first one up to the last one in the chain. During such traversal, the
-- stream object is able to bufferize the data or make transformations on the data.
--
-- The `Input_Stream` interface represents the stream to read data. It only provides a
-- `Read` procedure. The `Output_Stream` interface represents the stream to write data.
-- It provides a `Write`, `Flush` and `Close` operation.
--
-- @include util-streams-buffered.ads
-- @include util-streams-texts.ads
-- @include util-streams-files.ads
-- @include util-streams-pipes.ads
-- @include util-streams-sockets.ads
-- @include util-streams-raw.ads
-- @include util-streams-buffered-encoders.ads
package Util.Streams is
pragma Preelaborate;
-- -----------------------
-- Output stream
-- -----------------------
-- The <b>Output_Stream</b> is an interface that accepts output bytes
-- and sends them to a sink.
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is abstract;
-- Flush the buffer (if any) to the sink.
procedure Flush (Stream : in out Output_Stream) is null;
-- Close the sink.
procedure Close (Stream : in out Output_Stream) is null;
-- -----------------------
-- Input stream
-- -----------------------
-- The <b>Input_Stream</b> is the interface that reads input bytes
-- from a source and returns them.
type Input_Stream is limited interface;
type Input_Stream_Access is access all Input_Stream'Class;
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Input_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Copy the input stream to the output stream until the end of the input stream
-- is reached.
procedure Copy (From : in out Input_Stream'Class;
Into : in out Output_Stream'Class);
-- Copy the stream array to the string.
-- The string must be large enough to hold the stream array
-- or a Constraint_Error exception is raised.
procedure Copy (From : in Ada.Streams.Stream_Element_Array;
Into : in out String);
-- Copy the string to the stream array.
-- The stream array must be large enough to hold the string
-- or a Constraint_Error exception is raised.
procedure Copy (From : in String;
Into : in out Ada.Streams.Stream_Element_Array);
-- Notes:
-- ------
-- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b>
-- and <b>Input_Stream</b>. It is however not easy to use for composing various
-- stream behaviors.
end Util.Streams;
|
-----------------------------------------------------------------------
-- util-streams -- Stream utilities
-- Copyright (C) 2010, 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.Streams;
-- = Streams =
-- The `Util.Streams` package provides several types and operations to allow the
-- composition of input and output streams. Input streams can be chained together so that
-- they traverse the different stream objects when the data is read from them. Similarly,
-- output streams can be chained and the data that is written will traverse the different
-- streams from the first one up to the last one in the chain. During such traversal, the
-- stream object is able to bufferize the data or make transformations on the data.
--
-- The `Input_Stream` interface represents the stream to read data. It only provides a
-- `Read` procedure. The `Output_Stream` interface represents the stream to write data.
-- It provides a `Write`, `Flush` and `Close` operation.
--
-- @include util-streams-buffered.ads
-- @include util-streams-texts.ads
-- @include util-streams-files.ads
-- @include util-streams-pipes.ads
-- @include util-streams-sockets.ads
-- @include util-streams-raw.ads
-- @include util-streams-base16.ads
-- @include util-streams-base64.ads
-- @include util-streams-aes.ads
package Util.Streams is
pragma Preelaborate;
-- -----------------------
-- Output stream
-- -----------------------
-- The <b>Output_Stream</b> is an interface that accepts output bytes
-- and sends them to a sink.
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is abstract;
-- Flush the buffer (if any) to the sink.
procedure Flush (Stream : in out Output_Stream) is null;
-- Close the sink.
procedure Close (Stream : in out Output_Stream) is null;
-- -----------------------
-- Input stream
-- -----------------------
-- The <b>Input_Stream</b> is the interface that reads input bytes
-- from a source and returns them.
type Input_Stream is limited interface;
type Input_Stream_Access is access all Input_Stream'Class;
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Input_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Copy the input stream to the output stream until the end of the input stream
-- is reached.
procedure Copy (From : in out Input_Stream'Class;
Into : in out Output_Stream'Class);
-- Copy the stream array to the string.
-- The string must be large enough to hold the stream array
-- or a Constraint_Error exception is raised.
procedure Copy (From : in Ada.Streams.Stream_Element_Array;
Into : in out String);
-- Copy the string to the stream array.
-- The stream array must be large enough to hold the string
-- or a Constraint_Error exception is raised.
procedure Copy (From : in String;
Into : in out Ada.Streams.Stream_Element_Array);
-- Notes:
-- ------
-- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b>
-- and <b>Input_Stream</b>. It is however not easy to use for composing various
-- stream behaviors.
end Util.Streams;
|
Document the base16, base64, AES streams
|
Document the base16, base64, AES streams
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
58215de61a0e47cf102e5f79e8df595f827d617d
|
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, 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;
Folder_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- 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 out Storage_List_Bean);
-- Load the list of folders.
procedure Load_Folders (Storage : in out Storage_List_Bean);
-- Load the list of files associated with the current folder.
procedure Load_Files (Storage : in out 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
function Get_Value (From : in Storage_Bean;
Name : in String) return Util.Beans.Objects.Object;
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;
-- Returns true if the given mime type can be displayed by a browser.
-- Mime types: application/pdf, text/*, image/*
function Is_Browser_Visible (Mime_Type : in String) return Boolean;
end AWA.Storages.Beans;
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012, 2016, 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with 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.Folder_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.
overriding
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Folder_Bean bean instance.
function Create_Folder_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
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;
Folder_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- 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 out Storage_List_Bean);
-- Load the list of folders.
procedure Load_Folders (Storage : in out Storage_List_Bean);
-- Load the list of files associated with the current folder.
procedure Load_Files (Storage : in out 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
function Get_Value (From : in Storage_Bean;
Name : in String) return Util.Beans.Objects.Object;
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;
-- Returns true if the given mime type can be displayed by a browser.
-- Mime types: application/pdf, text/*, image/*
function Is_Browser_Visible (Mime_Type : in String) return Boolean;
end AWA.Storages.Beans;
|
Add Create_Folder_Bean and use the generated bean model for Folder_Bean
|
Add Create_Folder_Bean and use the generated bean model for Folder_Bean
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
fe107d4b171ef783e5b95a2a0c448d9031512f01
|
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.Sessions;
with ADO.Sessions.Entities;
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.Identifier (Util.Beans.Objects.To_Integer (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.Identifier (Util.Beans.Objects.To_Integer (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.Identifier (Util.Beans.Objects.To_Integer (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
begin
return AWA.Questions.Models.Question_Info_List_Bean (From).Get_Value (Name);
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, Session, Query);
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;
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.all, Session, Query);
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 : ADO.Identifier := ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (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 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
begin
return AWA.Questions.Models.Question_Info_List_Bean (From).Get_Value (Name);
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, Session, Query);
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;
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.all, Session, Query);
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;
|
Use the ADO.Utils.To_Identifier operation
|
Use the ADO.Utils.To_Identifier operation
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
c0ca6d20be5712f452411cc9ca11adaad07f555a
|
src/natools-s_expressions-generic_caches.adb
|
src/natools-s_expressions-generic_caches.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.Generic_Caches is
--------------------
-- Tree Interface --
--------------------
procedure Append
(Exp : in out Tree;
Kind : in Node_Kind;
Data : in Atom_Access := null)
is
N : Node_Access;
begin
case Kind is
when Atom_Node =>
N := new Node'(Kind => Atom_Node,
Parent | Next => null, Data => Data);
when List_Node =>
N := new Node'(Kind => List_Node, Parent | Next | Child => null);
end case;
if Exp.Root = null then
pragma Assert (Exp.Last = null);
Exp.Root := N;
else
pragma Assert (Exp.Last /= null);
if Exp.Opening then
pragma Assert (Exp.Last.Kind = List_Node);
pragma Assert (Exp.Last.Child = null);
Exp.Last.Child := N;
N.Parent := Exp.Last;
else
pragma Assert (Exp.Last.Next = null);
Exp.Last.Next := N;
N.Parent := Exp.Last.Parent;
end if;
end if;
Exp.Last := N;
Exp.Opening := Kind = List_Node;
end Append;
procedure Close_List (Exp : in out Tree) is
begin
if Exp.Opening then
Exp.Opening := False;
elsif Exp.Last /= null and then Exp.Last.Parent /= null then
Exp.Last := Exp.Last.Parent;
end if;
end Close_List;
function Create_Tree return Tree is
begin
return Tree'(Ada.Finalization.Limited_Controlled
with Root | Last => null, Opening => False);
end Create_Tree;
function Duplicate (Source : Tree) return Tree is
function Dup_List (First, Parent : Node_Access) return Node_Access;
function Dup_Node (N : not null Node_Access; Parent : Node_Access)
return Node_Access;
New_Last : Node_Access := null;
function Dup_List (First, Parent : Node_Access) return Node_Access is
Source : Node_Access := First;
Result, Target : Node_Access;
begin
if First = null then
return null;
end if;
Result := Dup_Node (First, Parent);
Target := Result;
loop
Source := Source.Next;
exit when Source = null;
Target.Next := Dup_Node (Source, Parent);
Target := Target.Next;
end loop;
return Result;
end Dup_List;
function Dup_Node (N : not null Node_Access; Parent : Node_Access)
return Node_Access
is
Result : Node_Access;
begin
case N.Kind is
when Atom_Node =>
Result := new Node'(Kind => Atom_Node,
Parent => Parent,
Next => null,
Data => new Atom'(N.Data.all));
when List_Node =>
Result := new Node'(Kind => List_Node,
Parent => Parent,
Next => null,
Child => null);
Result.Child := Dup_List (N.Child, Result);
end case;
if N = Source.Last then
New_Last := Result;
end if;
return Result;
end Dup_Node;
begin
return Result : Tree do
Result.Root := Dup_List (Source.Root, null);
pragma Assert ((New_Last = null) = (Source.Last = null));
Result.Last := New_Last;
Result.Opening := Source.Opening;
end return;
end Duplicate;
overriding procedure Finalize (Object : in out Tree) is
procedure List_Free (First : in out Node_Access);
procedure List_Free (First : in out Node_Access) is
Next : Node_Access := First;
Cur : Node_Access;
begin
while Next /= null loop
Cur := Next;
case Cur.Kind is
when Atom_Node =>
Unchecked_Free (Cur.Data);
when List_Node =>
List_Free (Cur.Child);
end case;
Next := Cur.Next;
Unchecked_Free (Cur);
end loop;
First := null;
end List_Free;
begin
List_Free (Object.Root);
Object.Last := null;
Object.Opening := False;
end Finalize;
-----------------------
-- Writing Interface --
-----------------------
function Duplicate (Cache : Reference) return Reference is
function Dup_Tree return Tree;
function Dup_Tree return Tree is
begin
return Duplicate (Cache.Exp.Query.Data.all);
end Dup_Tree;
begin
return Reference'(Exp => Trees.Create (Dup_Tree'Access));
end Duplicate;
-----------------------
-- Printer Interface --
-----------------------
overriding procedure Open_List (Output : in out Reference) is
begin
Output.Exp.Update.Data.Append (List_Node);
end Open_List;
overriding procedure Append_Atom
(Output : in out Reference; Data : in Atom) is
begin
if Output.Exp.Is_Empty then
Output.Exp.Replace (Create_Tree'Access);
end if;
Output.Exp.Update.Data.Append (Atom_Node, new Atom'(Data));
end Append_Atom;
overriding procedure Close_List (Output : in out Reference) is
begin
Output.Exp.Update.Data.Close_List;
end Close_List;
-------------------------
-- Reading Subprograms --
-------------------------
function First (Cache : Reference'Class) return Cursor is
N : Node_Access;
begin
if Cache.Exp.Is_Empty then
return Cursor'(others => <>);
else
N := Cache.Exp.Query.Data.Root;
pragma Assert (N /= null);
return Cursor'(Exp => Cache.Exp, Position => N,
Opening => N.Kind = List_Node);
end if;
end First;
--------------------------
-- Descriptor Interface --
--------------------------
overriding function Current_Event (Object : in Cursor)
return Events.Event is
begin
if Object.Position = null then
return Events.End_Of_Input;
end if;
case Object.Position.Kind is
when Atom_Node =>
return Events.Add_Atom;
when List_Node =>
if Object.Opening then
return Events.Open_List;
else
return Events.Close_List;
end if;
end case;
end Current_Event;
overriding function Current_Atom (Object : in Cursor) return Atom is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
return Object.Position.Data.all;
end Current_Atom;
overriding function Current_Level (Object : in Cursor) return Natural is
Result : Natural := 0;
N : Node_Access := Object.Position;
begin
if Object.Position /= null
and then Object.Position.Kind = List_Node
and then Object.Opening
then
Result := Result + 1;
end if;
while N /= null loop
Result := Result + 1;
N := N.Parent;
end loop;
return Natural'Max (Result, 1) - 1;
end Current_Level;
overriding procedure Query_Atom
(Object : in Cursor;
Process : not null access procedure (Data : in Atom)) is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
Process.all (Object.Position.Data.all);
end Query_Atom;
overriding procedure Read_Atom
(Object : in Cursor;
Data : out Atom;
Length : out Count)
is
Transferred : Count;
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
Length := Object.Position.Data'Length;
Transferred := Count'Min (Data'Length, Length);
Data (Data'First .. Data'First + Transferred - 1)
:= Object.Position.Data (Object.Position.Data'First
.. Object.Position.Data'First + Transferred - 1);
end Read_Atom;
overriding procedure Next
(Object : in out Cursor;
Event : out Events.Event) is
begin
if Object.Position = null then
Event := Events.Error;
return;
end if;
if Object.Opening then
pragma Assert (Object.Position.Kind = List_Node);
if Object.Position.Child = null then
Object.Opening := False;
else
pragma Assert (Object.Position.Child.Parent = Object.Position);
Object.Position := Object.Position.Child;
Object.Opening := Object.Position.Kind = List_Node;
end if;
elsif Object.Position.Next /= null then
pragma Assert (Object.Position.Next.Parent = Object.Position.Parent);
Object.Position := Object.Position.Next;
Object.Opening := Object.Position.Kind = List_Node;
elsif Object.Position.Parent /= null then
pragma Assert (Object.Position.Parent.Kind = List_Node);
Object.Position := Object.Position.Parent;
Object.Opening := False;
else
Object.Position := null;
end if;
Event := Object.Current_Event;
end Next;
end Natools.S_Expressions.Generic_Caches;
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.Generic_Caches is
--------------------
-- Tree Interface --
--------------------
procedure Append
(Exp : in out Tree;
Kind : in Node_Kind;
Data : in Atom_Access := null)
is
N : Node_Access;
begin
case Kind is
when Atom_Node =>
N := new Node'(Kind => Atom_Node,
Parent | Next => null, Data => Data);
when List_Node =>
N := new Node'(Kind => List_Node, Parent | Next | Child => null);
end case;
if Exp.Root = null then
pragma Assert (Exp.Last = null);
Exp.Root := N;
else
pragma Assert (Exp.Last /= null);
if Exp.Opening then
pragma Assert (Exp.Last.Kind = List_Node);
pragma Assert (Exp.Last.Child = null);
Exp.Last.Child := N;
N.Parent := Exp.Last;
else
pragma Assert (Exp.Last.Next = null);
Exp.Last.Next := N;
N.Parent := Exp.Last.Parent;
end if;
end if;
Exp.Last := N;
Exp.Opening := Kind = List_Node;
end Append;
procedure Close_List (Exp : in out Tree) is
begin
if Exp.Opening then
Exp.Opening := False;
elsif Exp.Last /= null and then Exp.Last.Parent /= null then
Exp.Last := Exp.Last.Parent;
end if;
end Close_List;
function Create_Tree return Tree is
begin
return Tree'(Ada.Finalization.Limited_Controlled
with Root | Last => null, Opening => False);
end Create_Tree;
function Duplicate (Source : Tree) return Tree is
function Dup_List (First, Parent : Node_Access) return Node_Access;
function Dup_Node (N : not null Node_Access; Parent : Node_Access)
return Node_Access;
New_Last : Node_Access := null;
function Dup_List (First, Parent : Node_Access) return Node_Access is
Source : Node_Access := First;
Result, Target : Node_Access;
begin
if First = null then
return null;
end if;
Result := Dup_Node (First, Parent);
Target := Result;
loop
Source := Source.Next;
exit when Source = null;
Target.Next := Dup_Node (Source, Parent);
Target := Target.Next;
end loop;
return Result;
end Dup_List;
function Dup_Node (N : not null Node_Access; Parent : Node_Access)
return Node_Access
is
Result : Node_Access;
begin
case N.Kind is
when Atom_Node =>
Result := new Node'(Kind => Atom_Node,
Parent => Parent,
Next => null,
Data => new Atom'(N.Data.all));
when List_Node =>
Result := new Node'(Kind => List_Node,
Parent => Parent,
Next => null,
Child => null);
Result.Child := Dup_List (N.Child, Result);
end case;
if N = Source.Last then
New_Last := Result;
end if;
return Result;
end Dup_Node;
begin
return Result : Tree do
Result.Root := Dup_List (Source.Root, null);
pragma Assert ((New_Last = null) = (Source.Last = null));
Result.Last := New_Last;
Result.Opening := Source.Opening;
end return;
end Duplicate;
overriding procedure Finalize (Object : in out Tree) is
procedure List_Free (First : in out Node_Access);
procedure List_Free (First : in out Node_Access) is
Next : Node_Access := First;
Cur : Node_Access;
begin
while Next /= null loop
Cur := Next;
case Cur.Kind is
when Atom_Node =>
Unchecked_Free (Cur.Data);
when List_Node =>
List_Free (Cur.Child);
end case;
Next := Cur.Next;
Unchecked_Free (Cur);
end loop;
First := null;
end List_Free;
begin
List_Free (Object.Root);
Object.Last := null;
Object.Opening := False;
end Finalize;
-----------------------
-- Writing Interface --
-----------------------
function Duplicate (Cache : Reference) return Reference is
function Dup_Tree return Tree;
function Dup_Tree return Tree is
begin
return Duplicate (Cache.Exp.Query.Data.all);
end Dup_Tree;
begin
return Reference'(Exp => Trees.Create (Dup_Tree'Access));
end Duplicate;
-----------------------
-- Printer Interface --
-----------------------
overriding procedure Open_List (Output : in out Reference) is
begin
Output.Exp.Update.Data.Append (List_Node);
end Open_List;
overriding procedure Append_Atom
(Output : in out Reference; Data : in Atom) is
begin
if Output.Exp.Is_Empty then
Output.Exp.Replace (Create_Tree'Access);
end if;
Output.Exp.Update.Data.Append (Atom_Node, new Atom'(Data));
end Append_Atom;
overriding procedure Close_List (Output : in out Reference) is
begin
Output.Exp.Update.Data.Close_List;
end Close_List;
-------------------------
-- Reading Subprograms --
-------------------------
function First (Cache : Reference'Class) return Cursor is
N : Node_Access;
begin
if Cache.Exp.Is_Empty then
return Cursor'(others => <>);
else
N := Cache.Exp.Query.Data.Root;
pragma Assert (N /= null);
return Cursor'(Exp => Cache.Exp, Position => N,
Opening => N.Kind = List_Node);
end if;
end First;
--------------------------
-- Descriptor Interface --
--------------------------
overriding function Current_Event (Object : in Cursor)
return Events.Event is
begin
if Object.Position = null then
return Events.End_Of_Input;
end if;
case Object.Position.Kind is
when Atom_Node =>
return Events.Add_Atom;
when List_Node =>
if Object.Opening then
return Events.Open_List;
else
return Events.Close_List;
end if;
end case;
end Current_Event;
overriding function Current_Atom (Object : in Cursor) return Atom is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
return Object.Position.Data.all;
end Current_Atom;
overriding function Current_Level (Object : in Cursor) return Natural is
Result : Natural := 0;
N : Node_Access := Object.Position;
begin
if Object.Position /= null
and then Object.Position.Kind = List_Node
and then Object.Opening
then
Result := Result + 1;
end if;
while N /= null loop
Result := Result + 1;
N := N.Parent;
end loop;
return Natural'Max (Result, 1) - 1;
end Current_Level;
overriding procedure Query_Atom
(Object : in Cursor;
Process : not null access procedure (Data : in Atom)) is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
Process.all (Object.Position.Data.all);
end Query_Atom;
overriding procedure Read_Atom
(Object : in Cursor;
Data : out Atom;
Length : out Count)
is
Transferred : Count;
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node then
raise Program_Error;
end if;
Length := Object.Position.Data'Length;
Transferred := Count'Min (Data'Length, Length);
Data (Data'First .. Data'First + Transferred - 1)
:= Object.Position.Data (Object.Position.Data'First
.. Object.Position.Data'First + Transferred - 1);
end Read_Atom;
overriding procedure Next
(Object : in out Cursor;
Event : out Events.Event) is
begin
if Object.Position = null then
Event := Events.End_Of_Input;
return;
end if;
if Object.Opening then
pragma Assert (Object.Position.Kind = List_Node);
if Object.Position.Child = null then
Object.Opening := False;
else
pragma Assert (Object.Position.Child.Parent = Object.Position);
Object.Position := Object.Position.Child;
Object.Opening := Object.Position.Kind = List_Node;
end if;
elsif Object.Position.Next /= null then
pragma Assert (Object.Position.Next.Parent = Object.Position.Parent);
Object.Position := Object.Position.Next;
Object.Opening := Object.Position.Kind = List_Node;
elsif Object.Position.Parent /= null then
pragma Assert (Object.Position.Parent.Kind = List_Node);
Object.Position := Object.Position.Parent;
Object.Opening := False;
else
Object.Position := null;
end if;
Event := Object.Current_Event;
end Next;
end Natools.S_Expressions.Generic_Caches;
|
return End_Of_Input instead of Error, to fix behaviour of empty cursors
|
s_expressions-generic_caches: return End_Of_Input instead of Error, to fix behaviour of empty cursors
|
Ada
|
isc
|
faelys/natools
|
e8e1ac41f4bec00378df61174da1e432c84d3722
|
mat/src/mat-consoles-text.adb
|
mat/src/mat-consoles-text.adb
|
-----------------------------------------------------------------------
-- mat-consoles-text - Text console interface
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Interrupts;
with MAT.Commands;
package body MAT.Consoles.Text is
-- ------------------------------
-- Report an error message.
-- ------------------------------
overriding
procedure Error (Console : in out Console_Type;
Message : in String) is
pragma Unreferenced (Console);
begin
Ada.Text_IO.Put_Line (Message);
end Error;
-- ------------------------------
-- Report a notice message.
-- ------------------------------
overriding
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String) is
pragma Unreferenced (Console, Kind);
begin
Ada.Text_IO.Put_Line (Message);
end Notice;
-- ------------------------------
-- Print the field value for the given field.
-- ------------------------------
overriding
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String;
Justify : in Justify_Type := J_LEFT) is
use type Ada.Text_IO.Count;
Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field));
Size : constant Natural := Console.Sizes (Field);
Start : Natural := Value'First;
Last : constant Natural := Value'Last;
Pad : Natural := 0;
begin
case Justify is
when J_LEFT =>
if Value'Length > Size then
Start := Last - Size + 1;
end if;
when J_RIGHT =>
if Value'Length < Size then
Pad := Size - Value'Length - 1;
else
Start := Last - Size + 1;
end if;
when J_CENTER =>
if Value'Length < Size then
Pad := (Size - Value'Length) / 2;
else
Start := Last - Size + 1;
end if;
when J_RIGHT_NO_FILL =>
if Value'Length >= Size then
Start := Last - Size + 1;
end if;
end case;
if Pad > 0 then
Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad));
elsif Pos > 1 then
Ada.Text_IO.Set_Col (Pos);
end if;
Ada.Text_IO.Put (Value (Start .. Last));
end Print_Field;
-- ------------------------------
-- Print the title for the given field.
-- ------------------------------
overriding
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is
use type Ada.Text_IO.Count;
Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field));
begin
if Pos > 1 then
Ada.Text_IO.Set_Col (Pos);
end if;
Ada.Text_IO.Put (Title);
end Print_Title;
-- ------------------------------
-- Start a new title in a report.
-- ------------------------------
overriding
procedure Start_Title (Console : in out Console_Type) is
begin
Console.Field_Count := 0;
Console.Sizes := (others => 0);
Console.Cols := (others => 1);
end Start_Title;
-- ------------------------------
-- Finish a new title in a report.
-- ------------------------------
procedure End_Title (Console : in out Console_Type) is
pragma Unreferenced (Console);
begin
Ada.Text_IO.New_Line;
end End_Title;
-- ------------------------------
-- Start a new row in a report.
-- ------------------------------
overriding
procedure Start_Row (Console : in out Console_Type) is
pragma Unreferenced (Console);
begin
if MAT.Interrupts.Is_Interrupted then
raise MAT.Commands.Stop_Command;
end if;
end Start_Row;
-- ------------------------------
-- Finish a new row in a report.
-- ------------------------------
overriding
procedure End_Row (Console : in out Console_Type) is
pragma Unreferenced (Console);
begin
Ada.Text_IO.New_Line;
end End_Row;
end MAT.Consoles.Text;
|
-----------------------------------------------------------------------
-- mat-consoles-text - Text console interface
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ANSI;
with MAT.Interrupts;
with MAT.Commands;
package body MAT.Consoles.Text is
-- ------------------------------
-- Report an error message.
-- ------------------------------
overriding
procedure Error (Console : in out Console_Type;
Message : in String) is
begin
Ada.Text_IO.Put (ANSI.Foreground (ANSI.Red));
Ada.Text_IO.Put (Message);
Ada.Text_IO.Put (ANSI.Reset);
Ada.Text_IO.New_Line;
Console.Cur_Col := 0;
end Error;
-- ------------------------------
-- Report a notice message.
-- ------------------------------
overriding
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String) is
pragma Unreferenced (Kind);
begin
Ada.Text_IO.Put (ANSI.Foreground (ANSI.Blue));
Ada.Text_IO.Put (Message);
Ada.Text_IO.Put (ANSI.Reset);
Ada.Text_IO.New_Line;
Console.Cur_Col := 0;
end Notice;
-- ------------------------------
-- Print the field value for the given field.
-- ------------------------------
overriding
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String;
Justify : in Justify_Type := J_LEFT) is
use type Ada.Text_IO.Count;
Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field));
Size : constant Natural := Console.Sizes (Field);
Start : Natural := Value'First;
Last : constant Natural := Value'Last;
Pad : Natural := 0;
begin
case Justify is
when J_LEFT =>
if Value'Length > Size then
Start := Last - Size + 1;
end if;
when J_RIGHT =>
if Value'Length < Size then
Pad := Size - Value'Length - 1;
else
Start := Last - Size + 1;
end if;
when J_CENTER =>
if Value'Length < Size then
Pad := (Size - Value'Length) / 2;
else
Start := Last - Size + 1;
end if;
when J_RIGHT_NO_FILL =>
if Value'Length >= Size then
Start := Last - Size + 1;
end if;
end case;
if Pad > 0 then
Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad));
elsif Pos > 1 then
Ada.Text_IO.Set_Col (Pos);
end if;
Ada.Text_IO.Put (Value (Start .. Last));
Console.Cur_Col := Console.Cur_Col + Ada.Text_IO.Count (Last - Start + 1);
end Print_Field;
-- ------------------------------
-- Print the title for the given field.
-- ------------------------------
overriding
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is
use type Ada.Text_IO.Count;
Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field));
begin
if Pos > 1 then
while Console.Cur_Col < Pos loop
Ada.Text_IO.Put (' ');
Console.Cur_Col := Console.Cur_Col + 1;
end loop;
end if;
Ada.Text_IO.Put (Title);
Console.Cur_Col := Console.Cur_Col + Title'Length;
end Print_Title;
-- ------------------------------
-- Start a new title in a report.
-- ------------------------------
overriding
procedure Start_Title (Console : in out Console_Type) is
begin
Console.Field_Count := 0;
Console.Sizes := (others => 0);
Console.Cols := (others => 1);
Ada.Text_IO.Put (Ansi.Style (Ansi.Bright, Ansi.On));
Ada.Text_IO.Put (ANSI.Foreground (ANSI.Light_Cyan));
Console.Cur_Col := 0;
end Start_Title;
-- ------------------------------
-- Finish a new title in a report.
-- ------------------------------
procedure End_Title (Console : in out Console_Type) is
begin
Ada.Text_Io.Put (ANSI.Reset);
Ada.Text_IO.New_Line;
Console.Cur_Col := 0;
end End_Title;
-- ------------------------------
-- Start a new row in a report.
-- ------------------------------
overriding
procedure Start_Row (Console : in out Console_Type) is
pragma Unreferenced (Console);
begin
if MAT.Interrupts.Is_Interrupted then
raise MAT.Commands.Stop_Command;
end if;
end Start_Row;
-- ------------------------------
-- Finish a new row in a report.
-- ------------------------------
overriding
procedure End_Row (Console : in out Console_Type) is
begin
Ada.Text_IO.New_Line;
Console.Cur_Col := 0;
end End_Row;
end MAT.Consoles.Text;
|
Add support to use ANSI colors
|
Add support to use ANSI colors
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
85685ff264f72d8665689df6041858cc05dc6abe
|
awa/plugins/awa-comments/src/awa-comments-beans.adb
|
awa/plugins/awa-comments/src/awa-comments-beans.adb
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions.Entities;
with ADO.Queries;
with ADO.Utils;
with AWA.Services.Contexts;
package body AWA.Comments.Beans is
package ASC renames AWA.Services.Contexts;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Comment_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Comment_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "comment" then
From.Set_Message (Util.Beans.Objects.To_String (Value));
elsif Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "status" then
From.Set_Status (AWA.Comments.Models.Status_Type_Objects.To_Value (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Module.Load_Comment (From, Id);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the comment.
-- ------------------------------
overriding
procedure Create (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Create_Comment (Permission => Ada.Strings.Unbounded.To_String (Bean.Permission),
Entity_Type => Ada.Strings.Unbounded.To_String (Bean.Entity_Type),
Comment => Bean);
end Create;
-- Save the comment.
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Save;
-- ------------------------------
-- Delete the comment.
-- ------------------------------
overriding
procedure Delete (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean);
end Delete;
-- ------------------------------
-- Create a new comment bean instance.
-- ------------------------------
function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_Bean_Access := new Comment_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "entity_id" then
From.Load_Comments (ADO.Utils.To_Identifier (Value));
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) with which the comments are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a comment on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
For_Entity_Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Into.Module.Get_Session;
begin
Into.Load_Comments (Session, For_Entity_Id);
end Load_Comments;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in out ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Into.Entity_Id := For_Entity_Id;
Query.Set_Query (AWA.Comments.Models.Query_Comment_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED)));
AWA.Comments.Models.List (Into, Session, Query);
end Load_Comments;
-- ------------------------------
-- Create the comment list bean instance.
-- ------------------------------
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_List_Bean_Access := new Comment_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_List_Bean;
end AWA.Comments.Beans;
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions.Entities;
with ADO.Queries;
with ADO.Utils;
with AWA.Services.Contexts;
package body AWA.Comments.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Comment_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Comment_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "message" then
From.Set_Message (Util.Beans.Objects.To_String (Value));
elsif Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "entity_id" then
declare
use type ADO.Identifier;
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
if Id /= ADO.NO_IDENTIFIER then
From.Set_Entity_Id (ADO.Utils.To_Identifier (Value));
end if;
end;
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "status" then
From.Set_Status (AWA.Comments.Models.Status_Type_Objects.To_Value (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Module.Load_Comment (From, Id);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the comment.
-- ------------------------------
overriding
procedure Create (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Create_Comment (Permission => Ada.Strings.Unbounded.To_String (Bean.Permission),
Entity_Type => Ada.Strings.Unbounded.To_String (Bean.Entity_Type),
Comment => Bean);
end Create;
-- Save the comment.
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Save;
-- ------------------------------
-- Delete the comment.
-- ------------------------------
overriding
procedure Delete (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean);
end Delete;
-- ------------------------------
-- Create a new comment bean instance.
-- ------------------------------
function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_Bean_Access := new Comment_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_Bean;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "entity_type" then
From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "permission" then
From.Permission := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "entity_id" then
From.Load_Comments (ADO.Utils.To_Identifier (Value));
end if;
end Set_Value;
-- ------------------------------
-- Set the entity type (database table) with which the comments are associated.
-- ------------------------------
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access) is
begin
Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all);
end Set_Entity_Type;
-- ------------------------------
-- Set the permission to check before removing or adding a comment on the entity.
-- ------------------------------
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String) is
begin
Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission);
end Set_Permission;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
For_Entity_Id : in ADO.Identifier) is
Session : ADO.Sessions.Session := Into.Module.Get_Session;
begin
Into.Load_Comments (Session, For_Entity_Id);
end Load_Comments;
-- ------------------------------
-- Load the comments associated with the given database identifier.
-- ------------------------------
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in out ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier) is
use ADO.Sessions.Entities;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type);
Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type);
Query : ADO.Queries.Context;
begin
Into.Entity_Id := For_Entity_Id;
Query.Set_Query (AWA.Comments.Models.Query_Comment_List);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", For_Entity_Id);
Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED)));
AWA.Comments.Models.List (Into, Session, Query);
end Load_Comments;
-- ------------------------------
-- Create the comment list bean instance.
-- ------------------------------
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Comment_List_Bean_Access := new Comment_List_Bean;
begin
Result.Module := Module;
return Result.all'Access;
end Create_Comment_List_Bean;
end AWA.Comments.Beans;
|
Fix the comment bean implementation
|
Fix the comment bean implementation
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
9787631479b14df354fdf375b5f7d2e93ab194a3
|
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 security frameworks 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.
--
-- @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;
--
-- -- Returns true if the given role is stored in the user principal.
-- function Has_Role (User : in Principal;
-- Role : in Role_Type) return Boolean is abstract;
-- 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 security frameworks 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.
--
-- @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;
|
Make the Principal be a real principal (ie, no knowledge of roles)
|
Make the Principal be a real principal (ie, no knowledge of roles)
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
257c58ebb747f0c52bba81383236e08cc62f3ffa
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Methods;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Ref
and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Blog_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Create a new blog.
procedure Create_Blog (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
type Post_Bean is new Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Post : AWA.Blogs.Models.Post_Ref;
Blog_Id : ADO.Identifier;
Title : Ada.Strings.Unbounded.Unbounded_String;
Text : Ada.Strings.Unbounded.Unbounded_String;
URI : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- This bean provides some methods that can be used in a Method_Expression
overriding
function Get_Method_Bindings (From : in Post_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create a new post.
procedure Create_Post (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
procedure Delete_Post (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Admin_Post_List_Bean bean instance.
function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Blog_List_Bean bean instance.
function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Blogs.Beans;
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Admin_Post_List_Bean bean instance.
function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Blog_List_Bean bean instance.
function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Blogs.Beans;
|
Use the UML generated Ada bean - implement the Save and Delete operations defined by the UML model - simplify the implementation
|
Use the UML generated Ada bean
- implement the Save and Delete operations defined by the UML model
- simplify the implementation
|
Ada
|
apache-2.0
|
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
f862701b848b9118bde8c22ba064270a449318c0
|
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, 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.Users.Models;
with AWA.Users.Principals;
with AWA.Permissions.Services;
with AWA.Modules;
with AWA.Modules.Lifecycles;
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");
package User_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Users.Models.User_Ref'Class);
subtype Listener is User_Lifecycle.Listener;
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);
-- Create a user in the database with the given user information and
-- the associated email address and for the given access key. The access key is first
-- verified and the user instance associated with it is retrieved. Verify that the email
-- address is unique and can be used by the user. Since the access key is verified,
-- grant immediately the access by opening a session and setting up the principal instance.
-- 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;
Key : in String;
IpAddr : in String;
Principal : out AWA.Users.Principals.Principal_Access);
-- 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;
Permissions : AWA.Permissions.Services.Permission_Manager_Access;
end record;
end AWA.Users.Services;
|
-----------------------------------------------------------------------
-- awa.users -- User registration, authentication processes
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with AWA.Users.Models;
with AWA.Users.Principals;
with AWA.Permissions.Services;
with AWA.Modules;
with AWA.Modules.Lifecycles;
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");
package User_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Users.Models.User_Ref'Class);
subtype Listener is User_Lifecycle.Listener;
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);
-- Create a user in the database with the given user information and
-- the associated email address and for the given access key. The access key is first
-- verified and the user instance associated with it is retrieved. Verify that the email
-- address is unique and can be used by the user. Since the access key is verified,
-- grant immediately the access by opening a session and setting up the principal instance.
-- 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;
Key : in String;
IpAddr : in String;
Principal : out AWA.Users.Principals.Principal_Access);
-- Load the user and email address from the invitation key.
procedure Load_User (Model : in out User_Service;
User : in out User_Ref'Class;
Email : in out Email_Ref'Class;
Key : in String);
-- 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;
Permissions : AWA.Permissions.Services.Permission_Manager_Access;
end record;
end AWA.Users.Services;
|
Declare the Load_User procedure
|
Declare the Load_User procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0b2ef09848447d4c2fd97dc2750722e18cca3821
|
src/sys/serialize/util-serialize-io-json.ads
|
src/sys/serialize/util-serialize-io-json.ads
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams;
with Util.Streams.Texts;
with Util.Stacks;
with Util.Beans.Objects;
package Util.Serialize.IO.JSON is
-- ------------------------------
-- JSON Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a JSON output stream.
-- The stream object takes care of the JSON escape rules.
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private;
-- Set the target output stream.
procedure Initialize (Stream : in out Output_Stream;
Output : in Util.Streams.Texts.Print_Stream_Access);
-- Flush the buffer (if any) to the sink.
overriding
procedure Flush (Stream : in out Output_Stream);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Output_Stream;
Item : in Wide_Wide_Character);
-- Start a JSON document. This operation writes the initial JSON marker ('{').
overriding
procedure Start_Document (Stream : in out Output_Stream);
-- Finish a JSON document by writing the final JSON marker ('}').
overriding
procedure End_Document (Stream : in out Output_Stream);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in String);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_Wide_String (Stream : in out Output_Stream;
Value : in Wide_Wide_String);
-- Start a new JSON object. If the name is not empty, write it as a string
-- followed by the ':' (colon). The JSON object starts with '{' (curly brace).
-- Example: "list": {
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String);
-- Terminates the current JSON object.
procedure End_Entity (Stream : in out Output_Stream;
Name : in String);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
-- Write a JSON name/value pair. The value is written according to its type
-- Example: "name": null
-- "name": false
-- "name": 12
-- "name": "value"
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the attribute with a null value.
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String);
-- Write a JSON name/value pair (see Write_Attribute).
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write a JSON name/value pair (see Write_Attribute).
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
-- Write an entity with a null value.
overriding
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String);
-- Starts a JSON array.
-- Example: "list": [
overriding
procedure Start_Array (Stream : in out Output_Stream;
Name : in String);
-- Terminates a JSON array.
overriding
procedure End_Array (Stream : in out Output_Stream;
Name : in String);
type Parser is new Serialize.IO.Parser with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class;
Sink : in out Reader'Class);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- Read a JSON file and return an object.
function Read (Path : in String) return Util.Beans.Objects.Object;
private
type Node_Info is record
Is_Array : Boolean := False;
Is_Root : Boolean := False;
Has_Fields : Boolean := False;
end record;
type Node_Info_Access is access all Node_Info;
package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info,
Element_Type_Access => Node_Info_Access);
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record
Stack : Node_Info_Stack.Stack;
Stream : Util.Streams.Texts.Print_Stream_Access;
end record;
procedure Write_Field_Name (Stream : in out Output_Stream;
Name : in String);
type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET,
T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE,
T_STRING, T_FLOAT, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL);
type Parser is new Util.Serialize.IO.Parser with record
Token : Ada.Strings.Unbounded.Unbounded_String;
Pending_Token : Token_Type := T_EOF;
Line_Number : Natural := 1;
Has_Pending_Char : Boolean := False;
Pending_Char : Character;
end record;
end Util.Serialize.IO.JSON;
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams;
with Util.Streams.Texts;
with Util.Stacks;
with Util.Properties;
with Util.Beans.Objects;
package Util.Serialize.IO.JSON is
-- ------------------------------
-- JSON Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a JSON output stream.
-- The stream object takes care of the JSON escape rules.
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private;
-- Set the target output stream.
procedure Initialize (Stream : in out Output_Stream;
Output : in Util.Streams.Texts.Print_Stream_Access);
-- Flush the buffer (if any) to the sink.
overriding
procedure Flush (Stream : in out Output_Stream);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Output_Stream;
Item : in Wide_Wide_Character);
-- Start a JSON document. This operation writes the initial JSON marker ('{').
overriding
procedure Start_Document (Stream : in out Output_Stream);
-- Finish a JSON document by writing the final JSON marker ('}').
overriding
procedure End_Document (Stream : in out Output_Stream);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in String);
-- Write the value as a JSON string. Special characters are escaped using the JSON
-- escape rules.
procedure Write_Wide_String (Stream : in out Output_Stream;
Value : in Wide_Wide_String);
-- Start a new JSON object. If the name is not empty, write it as a string
-- followed by the ':' (colon). The JSON object starts with '{' (curly brace).
-- Example: "list": {
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String);
-- Terminates the current JSON object.
procedure End_Entity (Stream : in out Output_Stream;
Name : in String);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
-- Write a JSON name/value pair. The value is written according to its type
-- Example: "name": null
-- "name": false
-- "name": 12
-- "name": "value"
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the attribute with a null value.
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String);
-- Write a JSON name/value pair (see Write_Attribute).
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write a JSON name/value pair (see Write_Attribute).
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
-- Write an entity with a null value.
overriding
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String);
-- Starts a JSON array.
-- Example: "list": [
overriding
procedure Start_Array (Stream : in out Output_Stream;
Name : in String);
-- Terminates a JSON array.
overriding
procedure End_Array (Stream : in out Output_Stream;
Name : in String);
type Parser is new Serialize.IO.Parser with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class;
Sink : in out Reader'Class);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- Read a JSON file and return an object.
function Read (Path : in String) return Util.Beans.Objects.Object;
function Read (Content : in String) return Util.Properties.Manager;
private
type Node_Info is record
Is_Array : Boolean := False;
Is_Root : Boolean := False;
Has_Fields : Boolean := False;
end record;
type Node_Info_Access is access all Node_Info;
package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info,
Element_Type_Access => Node_Info_Access);
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record
Stack : Node_Info_Stack.Stack;
Stream : Util.Streams.Texts.Print_Stream_Access;
end record;
procedure Write_Field_Name (Stream : in out Output_Stream;
Name : in String);
type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET,
T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE,
T_STRING, T_FLOAT, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL);
type Parser is new Util.Serialize.IO.Parser with record
Token : Ada.Strings.Unbounded.Unbounded_String;
Pending_Token : Token_Type := T_EOF;
Line_Number : Natural := 1;
Has_Pending_Char : Boolean := False;
Pending_Char : Character;
end record;
end Util.Serialize.IO.JSON;
|
Declare a Read function to easily read JSON content in property manager
|
Declare a Read function to easily read JSON content in property manager
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
2ec8c9fe79a8173c234ac01f12b58ff9cc094d13
|
mat/src/events/mat-events-probes.adb
|
mat/src/events/mat-events-probes.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := MAT.Frames.Create_Root;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Targets.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
Client.Event.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32);
Client.Event.Time := Client.Event.Time or Interfaces.Unsigned_64 (Time_Usec);
Frame.Cur_Depth := Count;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
MAT.Frames.Insert (Frame => Client.Frames,
Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
end MAT.Events.Probes;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := MAT.Frames.Create_Root;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Targets.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Tick_Ref;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Types.Target_Thread_Ref (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind));
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
Client.Event.Time := MAT.Types.Target_Tick_Ref (Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32));
Client.Event.Time := Client.Event.Time or MAT.Types.Target_Tick_Ref (Time_Usec);
Frame.Cur_Depth := Count;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
MAT.Frames.Insert (Frame => Client.Frames,
Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
end MAT.Events.Probes;
|
Use the Target_Tick_Ref type
|
Use the Target_Tick_Ref type
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
b6b6d68814fc5833de259c95dc5979112a3646b8
|
mat/regtests/mat-testsuite.adb
|
mat/regtests/mat-testsuite.adb
|
-----------------------------------------------------------------------
-- mat-testsuite - MAT Testsuite
-- 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.Readers.Tests;
with MAT.Targets.Tests;
package body MAT.Testsuite is
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Result : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
MAT.Readers.Tests.Add_Tests (Result);
MAT.Targets.Tests.Add_Tests (Result);
return Result;
end Suite;
end MAT.Testsuite;
|
-----------------------------------------------------------------------
-- mat-testsuite - MAT Testsuite
-- 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.Readers.Tests;
with MAT.Targets.Tests;
with MAT.Frames.Tests;
package body MAT.Testsuite is
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Result : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
MAT.Frames.Tests.Add_Tests (Result);
MAT.Readers.Tests.Add_Tests (Result);
MAT.Targets.Tests.Add_Tests (Result);
return Result;
end Suite;
end MAT.Testsuite;
|
Add the stack frames unit tests
|
Add the stack frames unit tests
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
bed49715d7534d1ddbc0ed9e8978ece7f364b0d5
|
regtests/security-policies-tests.adb
|
regtests/security-policies-tests.adb
|
-----------------------------------------------------------------------
-- Security-policies-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;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
with Security.Permissions.Tests;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)",
Test_Read_Empty_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Get the roles assigned to the user.
-- ------------------------------
function Get_Roles (User : in Test_Principal) return Roles.Role_Map is
begin
return User.Roles;
end Get_Roles;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
Map := (others => False);
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
-- Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager;
Name : in String) is
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Manager.Add_Policy (R.all'Access);
Manager.Add_Policy (U.all'Access);
Manager.Read_Policy (Util.Files.Compose (Path, Name));
end Configure_Policy;
-- ------------------------------
-- Test the Get_Policy, Get_Role_Policy and Add_Policy operations.
-- ------------------------------
procedure Test_Get_Role_Policy (T : in out Test) is
use type Roles.Role_Policy_Access;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P = null, "Get_Policy succeeded");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R = null, "Get_Role_Policy succeeded");
R := new Roles.Role_Policy;
M.Add_Policy (R.all'Access);
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P /= null, "Role policy not found");
T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R /= null, "Get_Role_Policy should not return null");
end Test_Get_Role_Policy;
-- ------------------------------
-- Test reading an empty policy file
-- ------------------------------
procedure Test_Read_Empty_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "empty.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
declare
Admin : Policies.Roles.Role_Type;
begin
Admin := R.Find_Role ("admin");
T.Fail ("'admin' role was returned");
exception
when Security.Policies.Roles.Invalid_Name =>
null;
end;
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission),
"Has_Permission (admin) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission),
"Has_Permission (create) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission),
"Has_Permission (update) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission),
"Has_Permission (delete) failed for empty policy");
end Test_Read_Empty_Policy;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
use Security.Permissions.Tests;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Admin : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
Configure_Policy (M, "simple-policy.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin := R.Find_Role ("admin");
T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was granted but user has no role");
User.Roles (Admin) := True;
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was not granted and user has admin role");
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
end;
declare
use Security.Permissions.Tests;
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/list.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (2);
User : aliased Test_Principal;
Admin : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
U : Security.Policies.URLs.URL_Policy_Access;
begin
Configure_Policy (M, File);
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
U := Security.Policies.URLs.Get_URL_Policy (M);
Admin := R.Find_Role (Role);
declare
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
-- A user without the role should not have the permission.
T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was granted for user without role. URI=" & URI);
-- Set the role.
User.Roles (Admin) := True;
T.Assert (U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was not granted for user with role. URI=" & URI);
end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
-----------------------------------------------------------------------
-- Security-policies-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;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
with Security.Permissions.Tests;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)",
Test_Read_Empty_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Get the roles assigned to the user.
-- ------------------------------
function Get_Roles (User : in Test_Principal) return Roles.Role_Map is
begin
return User.Roles;
end Get_Roles;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
Map := (others => False);
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
-- Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager;
Name : in String) is
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Manager.Add_Policy (R.all'Access);
Manager.Add_Policy (U.all'Access);
Manager.Read_Policy (Util.Files.Compose (Path, Name));
end Configure_Policy;
-- ------------------------------
-- Test the Get_Policy, Get_Role_Policy and Add_Policy operations.
-- ------------------------------
procedure Test_Get_Role_Policy (T : in out Test) is
use type Roles.Role_Policy_Access;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P = null, "Get_Policy succeeded");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R = null, "Get_Role_Policy succeeded");
R := new Roles.Role_Policy;
M.Add_Policy (R.all'Access);
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P /= null, "Role policy not found");
T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R /= null, "Get_Role_Policy should not return null");
end Test_Get_Role_Policy;
-- ------------------------------
-- Test reading an empty policy file
-- ------------------------------
procedure Test_Read_Empty_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "empty.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
declare
Admin : Policies.Roles.Role_Type;
begin
Admin := R.Find_Role ("admin");
T.Fail ("'admin' role was returned");
exception
when Security.Policies.Roles.Invalid_Name =>
null;
end;
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission),
"Has_Permission (admin) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission),
"Has_Permission (create) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission),
"Has_Permission (update) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission),
"Has_Permission (delete) failed for empty policy");
end Test_Read_Empty_Policy;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
use Security.Permissions.Tests;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Admin : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
Configure_Policy (M, "simple-policy.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin := R.Find_Role ("admin");
T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was granted but user has no role");
User.Roles (Admin) := True;
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was not granted and user has admin role");
declare
S : Util.Measures.Stamp;
Result : Boolean;
begin
for I in 1 .. 1_000 loop
Result := Contexts.Has_Permission (Permission => P_Admin.Permission);
end loop;
Util.Measures.Report (S, "Has_Permission role based (1000 calls)");
T.Assert (Result, "Permission not granted");
end;
declare
use Security.Permissions.Tests;
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/list.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (2);
User : aliased Test_Principal;
Admin : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
U : Security.Policies.URLs.URL_Policy_Access;
begin
Configure_Policy (M, File);
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
U := Security.Policies.URLs.Get_URL_Policy (M);
Admin := R.Find_Role (Role);
declare
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
-- A user without the role should not have the permission.
T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was granted for user without role. URI=" & URI);
-- Set the role.
User.Roles (Admin) := True;
T.Assert (U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was not granted for user with role. URI=" & URI);
end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
Fix benchmark test for Has_Permission
|
Fix benchmark test for Has_Permission
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
1ff758dc01268981c5880437f0ec2b9dee4fe3f9
|
regtests/ado-schemas-tests.adb
|
regtests/ado-schemas-tests.adb
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
with ADO.Parameters;
with ADO.Schemas.Databases;
with ADO.Sessions.Sources;
with ADO.Schemas.Entities;
with Regtests;
with Regtests.Simple.Model;
package body ADO.Schemas.Tests is
use Util.Tests;
function To_Lower_Case (S : in String) return String
renames Util.Strings.Transforms.To_Lower_Case;
package Caller is new Util.Test_Caller (Test, "ADO.Schemas");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type",
Test_Find_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)",
Test_Find_Entity_Type_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema",
Test_Load_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table",
Test_Table_Iterator'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)",
Test_Empty_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database",
Test_Create_Schema'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the entity cache and the Find_Entity_Type operation
-- ------------------------------
procedure Test_Find_Entity_Type (T : in out Test) is
S : ADO.Sessions.Session := Regtests.Get_Database;
C : ADO.Schemas.Entities.Entity_Cache;
begin
ADO.Schemas.Entities.Initialize (Cache => C,
Session => S);
declare
-- T1 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.USER_TABLE'Access);
-- T2 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access);
T4 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.ALLOCATE_TABLE);
T5 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
begin
-- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value");
-- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value");
T.Assert (T4 /= T5, "Two distinct tables have different entity types");
T.Assert (T4 > 0, "T1.Id must be positive");
T.Assert (T5 > 0, "T2.Id must be positive");
-- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids");
--
-- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4),
-- "Invalid entity type for allocate_table");
-- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5),
-- "Invalid entity type for user_table");
end;
end Test_Find_Entity_Type;
-- ------------------------------
-- Test calling Find_Entity_Type with an invalid table.
-- ------------------------------
procedure Test_Find_Entity_Type_Error (T : in out Test) is
C : ADO.Schemas.Entities.Entity_Cache;
begin
declare
R : ADO.Entity_Type;
pragma Unreferenced (R);
begin
R := Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
declare
P : ADO.Parameters.Parameter
:= ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0,
Len => 0, Value_Len => 0, Position => 0, Name => "");
begin
P := C.Expand ("something");
T.Assert (False, "Expand did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
end Test_Find_Entity_Type_Error;
-- ------------------------------
-- Test the Load_Schema operation and check the result schema.
-- ------------------------------
procedure Test_Load_Schema (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
begin
S.Load_Schema (Schema);
Table := ADO.Schemas.Find_Table (Schema, "allocate");
T.Assert (Table /= null, "Table schema for test_allocate not found");
Assert_Equals (T, "allocate", Get_Name (Table));
declare
C : Column_Cursor := Get_Columns (Table);
Nb_Columns : Integer := 0;
begin
while Has_Element (C) loop
Nb_Columns := Nb_Columns + 1;
Next (C);
end loop;
Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns");
end;
declare
C : constant Column_Definition := Find_Column (Table, "ID");
begin
T.Assert (C /= null, "Cannot find column 'id' in table schema");
Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "NAME");
begin
T.Assert (C /= null, "Cannot find column 'NAME' in table schema");
Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type");
T.Assert (Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "version");
begin
T.Assert (C /= null, "Cannot find column 'version' in table schema");
Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist");
begin
T.Assert (C = null, "Find_Column must return null for an unknown column");
end;
end Test_Load_Schema;
-- ------------------------------
-- Test the Table_Cursor operations and check the result schema.
-- ------------------------------
procedure Test_Table_Iterator (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
Driver : constant String := S.Get_Driver.Get_Driver_Name;
begin
S.Load_Schema (Schema);
declare
Iter : Table_Cursor := Schema.Get_Tables;
Count : Natural := 0;
begin
T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator");
while Has_Element (Iter) loop
Table := Element (Iter);
T.Assert (Table /= null, "Element function must not return null");
declare
Col_Iter : Column_Cursor := Get_Columns (Table);
begin
-- T.Assert (Has_Element (Col_Iter), "Table has a column");
while Has_Element (Col_Iter) loop
T.Assert (Element (Col_Iter) /= null, "Element function must not return null");
Next (Col_Iter);
end loop;
end;
Count := Count + 1;
Next (Iter);
end loop;
if Driver = "sqlite" then
Util.Tests.Assert_Equals (T, 15, Count,
"Invalid number of tables found in the schema");
elsif Driver = "mysql" then
Util.Tests.Assert_Equals (T, 8, Count,
"Invalid number of tables found in the schema");
elsif Driver = "postgresql" then
Util.Tests.Assert_Equals (T, 8, Count,
"Invalid number of tables found in the schema");
end if;
end;
end Test_Table_Iterator;
-- ------------------------------
-- Test the Table_Cursor operations on an empty schema.
-- ------------------------------
procedure Test_Empty_Schema (T : in out Test) is
Schema : Schema_Definition;
Iter : constant Table_Cursor := Schema.Get_Tables;
begin
T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator");
T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null");
end Test_Empty_Schema;
-- ------------------------------
-- Test the creation of database.
-- ------------------------------
procedure Test_Create_Schema (T : in out Test) is
use ADO.Sessions.Sources;
Msg : Util.Strings.Vectors.Vector;
Cfg : Data_Source := Data_Source (Regtests.Get_Controller);
Driver : constant String := Cfg.Get_Driver;
Database : constant String := Cfg.Get_Database;
Path : constant String :=
"db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql";
pragma Unreferenced (Msg);
begin
if Driver = "sqlite" then
if Ada.Directories.Exists (Database & ".test") then
Ada.Directories.Delete_File (Database & ".test");
end if;
Cfg.Set_Database (Database & ".test");
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
T.Assert (Ada.Directories.Exists (Database & ".test"),
"The sqlite database was not created");
else
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
end if;
end Test_Create_Schema;
end ADO.Schemas.Tests;
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
with ADO.Parameters;
with ADO.Schemas.Databases;
with ADO.Sessions.Sources;
with ADO.Schemas.Entities;
with Regtests;
with Regtests.Simple.Model;
package body ADO.Schemas.Tests is
use Util.Tests;
function To_Lower_Case (S : in String) return String
renames Util.Strings.Transforms.To_Lower_Case;
package Caller is new Util.Test_Caller (Test, "ADO.Schemas");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type",
Test_Find_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)",
Test_Find_Entity_Type_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema",
Test_Load_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table",
Test_Table_Iterator'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)",
Test_Empty_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database",
Test_Create_Schema'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the entity cache and the Find_Entity_Type operation
-- ------------------------------
procedure Test_Find_Entity_Type (T : in out Test) is
S : ADO.Sessions.Session := Regtests.Get_Database;
C : ADO.Schemas.Entities.Entity_Cache;
begin
ADO.Schemas.Entities.Initialize (Cache => C,
Session => S);
declare
-- T1 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.USER_TABLE'Access);
-- T2 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access);
T4 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.ALLOCATE_TABLE);
T5 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
begin
-- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value");
-- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value");
T.Assert (T4 /= T5, "Two distinct tables have different entity types");
T.Assert (T4 > 0, "T1.Id must be positive");
T.Assert (T5 > 0, "T2.Id must be positive");
-- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids");
--
-- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4),
-- "Invalid entity type for allocate_table");
-- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5),
-- "Invalid entity type for user_table");
end;
end Test_Find_Entity_Type;
-- ------------------------------
-- Test calling Find_Entity_Type with an invalid table.
-- ------------------------------
procedure Test_Find_Entity_Type_Error (T : in out Test) is
C : ADO.Schemas.Entities.Entity_Cache;
begin
declare
R : ADO.Entity_Type;
pragma Unreferenced (R);
begin
R := Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
declare
P : ADO.Parameters.Parameter
:= ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0,
Len => 0, Value_Len => 0, Position => 0, Name => "");
begin
P := C.Expand ("something");
T.Assert (False, "Expand did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
end Test_Find_Entity_Type_Error;
-- ------------------------------
-- Test the Load_Schema operation and check the result schema.
-- ------------------------------
procedure Test_Load_Schema (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
begin
S.Load_Schema (Schema);
Table := ADO.Schemas.Find_Table (Schema, "allocate");
T.Assert (Table /= null, "Table schema for test_allocate not found");
Assert_Equals (T, "allocate", Get_Name (Table));
declare
C : Column_Cursor := Get_Columns (Table);
Nb_Columns : Integer := 0;
begin
while Has_Element (C) loop
Nb_Columns := Nb_Columns + 1;
Next (C);
end loop;
Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns");
end;
declare
C : constant Column_Definition := Find_Column (Table, "ID");
begin
T.Assert (C /= null, "Cannot find column 'id' in table schema");
Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
T.Assert (Is_Primary (C), "Column must be a primary key");
end;
declare
C : constant Column_Definition := Find_Column (Table, "NAME");
begin
T.Assert (C /= null, "Cannot find column 'NAME' in table schema");
Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type");
T.Assert (Is_Null (C), "Column is null");
T.Assert (not Is_Primary (C), "Column must not be a primary key");
end;
declare
C : constant Column_Definition := Find_Column (Table, "version");
begin
T.Assert (C /= null, "Cannot find column 'version' in table schema");
Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist");
begin
T.Assert (C = null, "Find_Column must return null for an unknown column");
end;
end Test_Load_Schema;
-- ------------------------------
-- Test the Table_Cursor operations and check the result schema.
-- ------------------------------
procedure Test_Table_Iterator (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
Driver : constant String := S.Get_Driver.Get_Driver_Name;
begin
S.Load_Schema (Schema);
declare
Iter : Table_Cursor := Schema.Get_Tables;
Count : Natural := 0;
begin
T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator");
while Has_Element (Iter) loop
Table := Element (Iter);
T.Assert (Table /= null, "Element function must not return null");
declare
Col_Iter : Column_Cursor := Get_Columns (Table);
begin
-- T.Assert (Has_Element (Col_Iter), "Table has a column");
while Has_Element (Col_Iter) loop
T.Assert (Element (Col_Iter) /= null, "Element function must not return null");
Next (Col_Iter);
end loop;
end;
Count := Count + 1;
Next (Iter);
end loop;
if Driver = "sqlite" then
Util.Tests.Assert_Equals (T, 15, Count,
"Invalid number of tables found in the schema");
elsif Driver = "mysql" then
Util.Tests.Assert_Equals (T, 8, Count,
"Invalid number of tables found in the schema");
elsif Driver = "postgresql" then
Util.Tests.Assert_Equals (T, 8, Count,
"Invalid number of tables found in the schema");
end if;
end;
end Test_Table_Iterator;
-- ------------------------------
-- Test the Table_Cursor operations on an empty schema.
-- ------------------------------
procedure Test_Empty_Schema (T : in out Test) is
Schema : Schema_Definition;
Iter : constant Table_Cursor := Schema.Get_Tables;
begin
T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator");
T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null");
end Test_Empty_Schema;
-- ------------------------------
-- Test the creation of database.
-- ------------------------------
procedure Test_Create_Schema (T : in out Test) is
use ADO.Sessions.Sources;
Msg : Util.Strings.Vectors.Vector;
Cfg : Data_Source := Data_Source (Regtests.Get_Controller);
Driver : constant String := Cfg.Get_Driver;
Database : constant String := Cfg.Get_Database;
Path : constant String :=
"db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql";
pragma Unreferenced (Msg);
begin
if Driver = "sqlite" then
if Ada.Directories.Exists (Database & ".test") then
Ada.Directories.Delete_File (Database & ".test");
end if;
Cfg.Set_Database (Database & ".test");
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
T.Assert (Ada.Directories.Exists (Database & ".test"),
"The sqlite database was not created");
else
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
end if;
end Test_Create_Schema;
end ADO.Schemas.Tests;
|
Add tests for the Is_Primary function
|
Add tests for the Is_Primary function
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
98a63726d504b9c35a9fda0e7f2830dee90e08ce
|
src/wiki-streams-text_io.ads
|
src/wiki-streams-text_io.ads
|
-----------------------------------------------------------------------
-- wiki-streams-text_io -- Text_IO input output streams
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Wide_Wide_Text_IO;
-- === Text_IO Input and Output streams ===
-- The <tt>Wiki.Streams.Text_IO</tt> package defines the <tt>File_Input_Stream</tt> and
-- the <tt>File_Output_Stream</tt/ types which use the <tt>Ada.Wide_Wide_Text_IO</tt> package
-- to read or write the output streams.
--
-- By default the <tt>File_Input_Stream</tt> is configured to read the standard input.
-- The <tt>Open</tt> procedure can be used to read from a file knowing its name.
--
-- The <tt>File_Output_Stream</tt> is configured to write on the standard output.
-- The <tt>Open</tt> and <tt>Create</tt> procedure can be used to write on a file.
--
package Wiki.Streams.Text_IO is
type File_Input_Stream is limited new Wiki.Streams.Input_Stream with private;
type File_Input_Stream_Access is access all File_Input_Stream'Class;
-- Open the file and prepare to read the input stream.
procedure Open (Stream : in out File_Input_Stream;
Path : in String;
Form : in String := "");
-- Read one character from the input stream and return False to the <tt>Eof</tt> indicator.
-- When there is no character to read, return True in the <tt>Eof</tt> indicator.
overriding
procedure Read (Input : in out File_Input_Stream;
Char : out Wiki.Strings.WChar;
Eof : out Boolean);
type File_Output_Stream is limited new Wiki.Streams.Output_Stream with private;
type File_Output_Stream_Access is access all File_Output_Stream'Class;
-- Open the file and prepare to write the output stream.
procedure Open (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "");
-- Create the file and prepare to write the output stream.
procedure Create (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "");
-- Write the string to the output stream.
overriding
procedure Write (Stream : in out File_Output_Stream;
Content : in Wiki.Strings.WString);
-- Write a single character to the output stream.
overriding
procedure Write (Stream : in out File_Output_Stream;
Char : in Wiki.Strings.WChar);
private
type File_Input_Stream is limited new Wiki.Streams.Input_Stream with record
File : Ada.Wide_Wide_Text_IO.File_Type;
end record;
type File_Output_Stream is limited new Wiki.Streams.Output_Stream with record
File : Ada.Wide_Wide_Text_IO.File_Type := Ada.Wide_Wide_Text_IO.Current_Output;
end record;
end Wiki.Streams.Text_IO;
|
-----------------------------------------------------------------------
-- wiki-streams-text_io -- Text_IO input output streams
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Wide_Wide_Text_IO;
-- === Text_IO Input and Output streams ===
-- The <tt>Wiki.Streams.Text_IO</tt> package defines the <tt>File_Input_Stream</tt> and
-- the <tt>File_Output_Stream</tt/ types which use the <tt>Ada.Wide_Wide_Text_IO</tt> package
-- to read or write the output streams.
--
-- By default the <tt>File_Input_Stream</tt> is configured to read the standard input.
-- The <tt>Open</tt> procedure can be used to read from a file knowing its name.
--
-- The <tt>File_Output_Stream</tt> is configured to write on the standard output.
-- The <tt>Open</tt> and <tt>Create</tt> procedure can be used to write on a file.
--
package Wiki.Streams.Text_IO is
type File_Input_Stream is limited new Wiki.Streams.Input_Stream with private;
type File_Input_Stream_Access is access all File_Input_Stream'Class;
-- Open the file and prepare to read the input stream.
procedure Open (Stream : in out File_Input_Stream;
Path : in String;
Form : in String := "");
-- Read one character from the input stream and return False to the <tt>Eof</tt> indicator.
-- When there is no character to read, return True in the <tt>Eof</tt> indicator.
overriding
procedure Read (Input : in out File_Input_Stream;
Char : out Wiki.Strings.WChar;
Eof : out Boolean);
type File_Output_Stream is limited new Wiki.Streams.Output_Stream with private;
type File_Output_Stream_Access is access all File_Output_Stream'Class;
-- Open the file and prepare to write the output stream.
procedure Open (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "");
-- Close the file.
procedure Close (Stream : in out File_Input_Stream);
-- Create the file and prepare to write the output stream.
procedure Create (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "");
-- Write the string to the output stream.
overriding
procedure Write (Stream : in out File_Output_Stream;
Content : in Wiki.Strings.WString);
-- Write a single character to the output stream.
overriding
procedure Write (Stream : in out File_Output_Stream;
Char : in Wiki.Strings.WChar);
private
type File_Input_Stream is limited new Wiki.Streams.Input_Stream with record
File : Ada.Wide_Wide_Text_IO.File_Type;
end record;
type File_Output_Stream is limited new Wiki.Streams.Output_Stream with record
File : Ada.Wide_Wide_Text_IO.File_Type := Ada.Wide_Wide_Text_IO.Current_Output;
end record;
end Wiki.Streams.Text_IO;
|
Declare the Close procedure
|
Declare the Close procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
9ff7271de27665504003a5976e26b41c83ac15d0
|
awa/plugins/awa-images/regtests/awa-images-tests.adb
|
awa/plugins/awa-images/regtests/awa-images-tests.adb
|
-----------------------------------------------------------------------
-- awa-images-tests -- Unit tests for images module
-- Copyright (C) 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
with Util.Strings;
with ADO;
with Servlet.Requests.Mockup;
with Servlet.Responses.Mockup;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
package body AWA.Images.Tests is
use Ada.Strings.Unbounded;
use ADO;
package Caller is new Util.Test_Caller (Test, "Images.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Images.Beans.Create",
Test_Create_Image'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Servlets (missing)",
Test_Missing_Image'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
pragma Unreferenced (Title);
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/images.html",
"images-anonymous-list.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list recent page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Verify that the wiki lists contain the given page.
-- ------------------------------
procedure Verify_List_Contains (T : in out Test;
Name : in String) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html",
"storage-list.html");
ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply,
"List of documents is invalid");
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 image by simulating web requests.
-- ------------------------------
procedure Test_Create_Image (T : in out Test) is
Request : Servlet.Requests.Mockup.Part_Request (1);
Reply : Servlet.Responses.Mockup.Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
Folder_Id : ADO.Identifier;
Image_Id : ADO.Identifier;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/upload.jpg");
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
-- Create the folder.
Request.Set_Parameter ("folder-name", "Image Folder Name");
Request.Set_Parameter ("storage-folder-create-form", "1");
Request.Set_Parameter ("storage-folder-create-button", "1");
ASF.Tests.Do_Post (Request, Reply, "/storages/forms/folder-create.html",
"folder-create-form.html");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK,
"Invalid response after folder creation");
Reply.Read_Content (Content);
Folder_Id := AWA.Tests.Helpers.Extract_Identifier (To_String (Content), "#folder");
T.Assert (Folder_Id > 0, "Invalid folder id returned");
-- Check the list page.
ASF.Tests.Do_Get (Request, Reply, "/storages/images.html",
"image-list.html");
ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply,
"List of documents is invalid (title)");
ASF.Tests.Assert_Contains (T, "Image Folder Name", Reply,
"List of documents is invalid (content)");
-- Upload an image to the folder.
if Ada.Directories.Exists (Path) then
Ada.Directories.Delete_File (Path);
end if;
Ada.Directories.Copy_File (Source_Name => "regtests/files/images/Ada-Lovelace.jpg",
Target_Name => Path,
Form => "all");
Request.Set_Parameter ("folder", ADO.Identifier'Image (Folder_Id));
Request.Set_Parameter ("uploadForm", "1");
Request.Set_Parameter ("id", "-1");
Request.Set_Parameter ("upload-button", "1");
Request.Set_Part (Position => 1, Name => "upload-file",
Path => Path, Content_Type => "image/jpg");
ASF.Tests.Do_Post (Request, Reply, "/storages/forms/upload-form.html",
"upload-image-form.html");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK,
"Invalid response after image upload");
T.Assert_Equals ("application/json", Reply.Get_Content_Type,
"Invalid response after upload");
Reply.Read_Content (Content);
Image_Id := AWA.Tests.Helpers.Extract_Identifier (To_String (Content), "store");
T.Assert (Image_Id > 0, "Invalid image id returned after upload");
-- Look at the image content.
ASF.Tests.Do_Get (Request, Reply, "/storages/images/"
& Util.Strings.Image (Natural (Image_Id)) & "/view/upload.jpg",
"image-file-data.jpg");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK,
"Invalid response after image get");
T.Assert_Equals ("image/jpg", Reply.Get_Content_Type,
"Invalid response after upload");
-- Look at the image description page.
ASF.Tests.Do_Get (Request, Reply, "/storages/image-info/"
& Util.Strings.Image (Natural (Image_Id)),
"image-file-info.html");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK,
"Invalid response for image-info page");
T.Assert_Equals ("text/html; charset=UTF-8", Reply.Get_Content_Type,
"Invalid response for image-info");
ASF.Tests.Assert_Contains (T, "/storages/files/"
& Util.Strings.Image (Natural (Image_Id)) & "/", Reply,
"Image info page is invalid (missing link)");
end Test_Create_Image;
-- ------------------------------
-- Test getting an image which does not exist.
-- ------------------------------
procedure Test_Missing_Image (T : in out Test) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/images/12345345/view/missing.jpg",
"image-file-missing.html");
ASF.Tests.Assert_Matches (T, ".title.Page not found./title.", Reply,
"Page for a missing document is invalid",
Servlet.Responses.SC_NOT_FOUND);
end Test_Missing_Image;
end AWA.Images.Tests;
|
-----------------------------------------------------------------------
-- awa-images-tests -- Unit tests for images module
-- Copyright (C) 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
with Util.Strings;
with ADO;
with Servlet.Requests.Mockup;
with Servlet.Responses.Mockup;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
package body AWA.Images.Tests is
use Ada.Strings.Unbounded;
use ADO;
package Caller is new Util.Test_Caller (Test, "Images.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Images.Beans.Create",
Test_Create_Image'Access);
Caller.Add_Test (Suite, "Test AWA.Images.Servlets (missing)",
Test_Missing_Image'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
pragma Unreferenced (Title);
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/images.html",
"images-anonymous-list.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list recent page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Verify that the wiki lists contain the given page.
-- ------------------------------
procedure Verify_List_Contains (T : in out Test;
Name : in String) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html",
"storage-list.html");
ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply,
"List of documents is invalid");
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 image by simulating web requests.
-- ------------------------------
procedure Test_Create_Image (T : in out Test) is
Request : Servlet.Requests.Mockup.Part_Request (1);
Reply : Servlet.Responses.Mockup.Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
Folder_Id : ADO.Identifier;
Image_Id : ADO.Identifier;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/upload.jpg");
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
-- Create the folder.
Request.Set_Parameter ("folder-name", "Image Folder Name");
Request.Set_Parameter ("storage-folder-create-form", "1");
Request.Set_Parameter ("storage-folder-create-button", "1");
ASF.Tests.Do_Post (Request, Reply, "/storages/forms/folder-create.html",
"folder-create-form.html");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK,
"Invalid response after folder creation");
Reply.Read_Content (Content);
Folder_Id := AWA.Tests.Helpers.Extract_Identifier (To_String (Content), "#folder");
T.Assert (Folder_Id > 0, "Invalid folder id returned");
-- Check the list page.
ASF.Tests.Do_Get (Request, Reply, "/storages/images.html",
"image-list.html");
ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply,
"List of documents is invalid (title)");
ASF.Tests.Assert_Contains (T, "Image Folder Name", Reply,
"List of documents is invalid (content)");
-- Upload an image to the folder.
if Ada.Directories.Exists (Path) then
Ada.Directories.Delete_File (Path);
end if;
Ada.Directories.Copy_File (Source_Name => "regtests/files/images/Ada-Lovelace.jpg",
Target_Name => Path,
Form => "all");
Request.Set_Parameter ("folder", ADO.Identifier'Image (Folder_Id));
Request.Set_Parameter ("uploadForm", "1");
Request.Set_Parameter ("id", "-1");
Request.Set_Parameter ("upload-button", "1");
Request.Set_Part (Position => 1, Name => "upload-file",
Path => Path, Content_Type => "image/jpg");
ASF.Tests.Do_Post (Request, Reply, "/storages/forms/upload-form.html",
"upload-image-form.html");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK,
"Invalid response after image upload");
T.Assert_Equals ("application/json", Reply.Get_Content_Type,
"Invalid response after upload");
Reply.Read_Content (Content);
Image_Id := AWA.Tests.Helpers.Extract_Identifier (To_String (Content), "store");
T.Assert (Image_Id > 0, "Invalid image id returned after upload");
-- Look at the image content.
ASF.Tests.Do_Get (Request, Reply, "/storages/images/"
& Util.Strings.Image (Natural (Image_Id)) & "/view/upload.jpg",
"image-file-data.jpg");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK,
"Invalid response after image get");
T.Assert_Equals ("image/jpg", Reply.Get_Content_Type,
"Invalid response after upload");
-- Look at the image description page.
ASF.Tests.Do_Get (Request, Reply, "/storages/image-info/"
& Util.Strings.Image (Natural (Image_Id)),
"image-file-info.html");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK,
"Invalid response for image-info page");
T.Assert_Equals ("text/html; charset=UTF-8", Reply.Get_Content_Type,
"Invalid response for image-info");
ASF.Tests.Assert_Contains (T, "/storages/files/"
& Util.Strings.Image (Natural (Image_Id)) & "/", Reply,
"Image info page is invalid (missing link)");
end Test_Create_Image;
-- ------------------------------
-- Test getting an image which does not exist.
-- ------------------------------
procedure Test_Missing_Image (T : in out Test) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/storages/images/12345345/view/missing.jpg",
"image-file-missing.html");
ASF.Tests.Assert_Redirect (T, "/auth/login.html", Reply,
"Invalid redirection for protected page");
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/storages/images/12345345/view/missing.jpg",
"image-file-missing.html");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_NOT_FOUND,
"Invalid response after image get");
end Test_Missing_Image;
end AWA.Images.Tests;
|
Fix the Test_Missing_Image unit test
|
Fix the Test_Missing_Image unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
179fd8cce1aa394b2a2ff354c87ef0d40772e712
|
src/asf-lifecycles-default.adb
|
src/asf-lifecycles-default.adb
|
-----------------------------------------------------------------------
-- asf-lifecycles-default -- Default Lifecycle handler
-- 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.Lifecycles.Restore;
with ASF.Lifecycles.Apply;
with ASF.Lifecycles.Validation;
with ASF.Lifecycles.Update;
with ASF.Lifecycles.Invoke;
with ASF.Lifecycles.Response;
package body ASF.Lifecycles.Default is
-- ------------------------------
-- Creates the phase controllers by invoking the <b>Set_Controller</b>
-- procedure for each phase. This is called by <b>Initialize</b> to build
-- the lifecycle handler.
-- ------------------------------
procedure Create_Phase_Controllers (Controller : in out Lifecycle) is
use ASF.Events.Phases;
begin
Controller.Set_Controller (Phase => RESTORE_VIEW,
Instance => new Lifecycles.Restore.Restore_Controller);
Controller.Set_Controller (Phase => APPLY_REQUEST_VALUES,
Instance => new Lifecycles.Apply.Apply_Controller);
Controller.Set_Controller (Phase => PROCESS_VALIDATION,
Instance => new Lifecycles.Validation.Validation_Controller);
Controller.Set_Controller (Phase => UPDATE_MODEL_VALUES,
Instance => new Lifecycles.Update.Update_Controller);
Controller.Set_Controller (Phase => INVOKE_APPLICATION,
Instance => new Lifecycles.Invoke.Invoke_Controller);
Controller.Set_Controller (Phase => RENDER_RESPONSE,
Instance => new Lifecycles.Response.Response_Controller);
end Create_Phase_Controllers;
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
overriding
procedure Initialize (Controller : in out Lifecycle;
App : access ASF.Applications.Main.Application'Class) is
begin
Lifecycle'Class (Controller).Create_Phase_Controllers;
for Phase in Controller.Controllers'Range loop
Controller.Controllers (Phase).Initialize (App);
end loop;
end Initialize;
end ASF.Lifecycles.Default;
|
-----------------------------------------------------------------------
-- asf-lifecycles-default -- Default Lifecycle handler
-- Copyright (C) 2010, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Lifecycles.Restore;
with ASF.Lifecycles.Apply;
with ASF.Lifecycles.Validation;
with ASF.Lifecycles.Update;
with ASF.Lifecycles.Invoke;
with ASF.Lifecycles.Response;
package body ASF.Lifecycles.Default is
-- ------------------------------
-- Creates the phase controllers by invoking the <b>Set_Controller</b>
-- procedure for each phase. This is called by <b>Initialize</b> to build
-- the lifecycle handler.
-- ------------------------------
procedure Create_Phase_Controllers (Controller : in out Lifecycle) is
use ASF.Events.Phases;
begin
Controller.Set_Controller (Phase => RESTORE_VIEW,
Instance => new Lifecycles.Restore.Restore_Controller);
Controller.Set_Controller (Phase => APPLY_REQUEST_VALUES,
Instance => new Lifecycles.Apply.Apply_Controller);
Controller.Set_Controller (Phase => PROCESS_VALIDATION,
Instance => new Lifecycles.Validation.Validation_Controller);
Controller.Set_Controller (Phase => UPDATE_MODEL_VALUES,
Instance => new Lifecycles.Update.Update_Controller);
Controller.Set_Controller (Phase => INVOKE_APPLICATION,
Instance => new Lifecycles.Invoke.Invoke_Controller);
Controller.Set_Controller (Phase => RENDER_RESPONSE,
Instance => new Lifecycles.Response.Response_Controller);
end Create_Phase_Controllers;
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
overriding
procedure Initialize (Controller : in out Lifecycle;
Views : access ASF.Applications.Views.View_Handler'Class) is
begin
Lifecycle'Class (Controller).Create_Phase_Controllers;
for Phase in Controller.Controllers'Range loop
Controller.Controllers (Phase).Initialize (Views);
end loop;
end Initialize;
end ASF.Lifecycles.Default;
|
Update Initialize to use a ASF.Applications.Views.View_Handler'Class
|
Update Initialize to use a ASF.Applications.Views.View_Handler'Class
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
b89cc73f5eb2375e57008caef8c76861db7572e5
|
awa/plugins/awa-storages/src/awa-storages-modules.adb
|
awa/plugins/awa-storages/src/awa-storages-modules.adb
|
-----------------------------------------------------------------------
-- awa-storages-module -- Storage management module
-- 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 Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Applications;
with AWA.Storages.Beans.Factories;
package body AWA.Storages.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Module");
package Register is new AWA.Modules.Beans (Module => Storage_Module,
Module_Access => Storage_Module_Access);
-- ------------------------------
-- Initialize the storage module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Storage_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the storage module");
-- Setup the resource bundles.
App.Register ("storageMsg", "storages");
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Upload_Bean",
Handler => AWA.Storages.Beans.Create_Upload_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Folder_Bean",
Handler => AWA.Storages.Beans.Factories.Create_Folder_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Folder_List_Bean",
Handler => AWA.Storages.Beans.Create_Folder_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Storage_List_Bean",
Handler => AWA.Storages.Beans.Create_Storage_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Storage_Bean",
Handler => AWA.Storages.Beans.Create_Storage_Bean'Access);
App.Add_Servlet ("storage", Plugin.Storage_Servlet'Unchecked_Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Create the storage manager when everything is initialized.
Plugin.Manager := Plugin.Create_Storage_Manager;
end Initialize;
-- ------------------------------
-- Get the storage manager.
-- ------------------------------
function Get_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access is
begin
return Plugin.Manager;
end Get_Storage_Manager;
-- ------------------------------
-- Create a storage manager. This operation can be overriden to provide another
-- storage service implementation.
-- ------------------------------
function Create_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access is
Result : constant Services.Storage_Service_Access := new Services.Storage_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_Storage_Manager;
-- ------------------------------
-- Get the storage module instance associated with the current application.
-- ------------------------------
function Get_Storage_Module return Storage_Module_Access is
function Get is new AWA.Modules.Get (Storage_Module, Storage_Module_Access, NAME);
begin
return Get;
end Get_Storage_Module;
-- ------------------------------
-- Get the storage manager instance associated with the current application.
-- ------------------------------
function Get_Storage_Manager return Services.Storage_Service_Access is
Module : constant Storage_Module_Access := Get_Storage_Module;
begin
if Module = null then
Log.Error ("There is no active Storage_Module");
return null;
else
return Module.Get_Storage_Manager;
end if;
end Get_Storage_Manager;
end AWA.Storages.Modules;
|
-----------------------------------------------------------------------
-- awa-storages-module -- Storage management module
-- Copyright (C) 2012, 2016, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Applications;
with AWA.Storages.Beans.Factories;
package body AWA.Storages.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Module");
package Register is new AWA.Modules.Beans (Module => Storage_Module,
Module_Access => Storage_Module_Access);
-- ------------------------------
-- Initialize the storage module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Storage_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the storage module");
-- Setup the resource bundles.
App.Register ("storageMsg", "storages");
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Upload_Bean",
Handler => AWA.Storages.Beans.Create_Upload_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Folder_Bean",
Handler => AWA.Storages.Beans.Factories.Create_Folder_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Folder_List_Bean",
Handler => AWA.Storages.Beans.Create_Folder_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Storage_List_Bean",
Handler => AWA.Storages.Beans.Create_Storage_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Storages.Beans.Storage_Bean",
Handler => AWA.Storages.Beans.Create_Storage_Bean'Access);
App.Add_Servlet ("storage", Plugin.Storage_Servlet'Unchecked_Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Storage_Module;
Props : in ASF.Applications.Config) is
begin
-- Create the storage manager when everything is initialized.
Plugin.Manager := Plugin.Create_Storage_Manager;
end Configure;
-- ------------------------------
-- Get the storage manager.
-- ------------------------------
function Get_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access is
begin
return Plugin.Manager;
end Get_Storage_Manager;
-- ------------------------------
-- Create a storage manager. This operation can be overriden to provide another
-- storage service implementation.
-- ------------------------------
function Create_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access is
Result : constant Services.Storage_Service_Access := new Services.Storage_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_Storage_Manager;
-- ------------------------------
-- Get the storage module instance associated with the current application.
-- ------------------------------
function Get_Storage_Module return Storage_Module_Access is
function Get is new AWA.Modules.Get (Storage_Module, Storage_Module_Access, NAME);
begin
return Get;
end Get_Storage_Module;
-- ------------------------------
-- Get the storage manager instance associated with the current application.
-- ------------------------------
function Get_Storage_Manager return Services.Storage_Service_Access is
Module : constant Storage_Module_Access := Get_Storage_Module;
begin
if Module = null then
Log.Error ("There is no active Storage_Module");
return null;
else
return Module.Get_Storage_Manager;
end if;
end Get_Storage_Manager;
end AWA.Storages.Modules;
|
Add Configure procedure to allow the configuration of the storage service
|
Add Configure procedure to allow the configuration of the storage service
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ebe71a083ee0bf67306a16ac3b21d8681a4de246
|
mat/src/events/mat-events-probes.adb
|
mat/src/events/mat-events-probes.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := MAT.Frames.Create_Root;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Targets.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type Interfaces.Unsigned_64;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
Client.Event.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32);
Client.Event.Time := Client.Event.Time or Interfaces.Unsigned_64 (Time_Usec);
Frame.Cur_Depth := Count;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
MAT.Frames.Insert (Frame => Client.Frames,
Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
-- ------------------------------
-- Read the event data stream headers with the event description.
-- Configure the reader to analyze the data stream according to the event descriptions.
-- ------------------------------
procedure Read_Headers (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
begin
Client.Read_Event_Definitions (Msg);
Client.Frame := new MAT.Events.Frame_Info (512);
exception
when E : others =>
Log.Error ("Exception while reading headers ", E);
end Read_Headers;
end MAT.Events.Probes;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := MAT.Frames.Create_Root;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Targets.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop
if Count < Frame.Depth then
Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
Client.Event.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32);
Client.Event.Time := Client.Event.Time or Interfaces.Unsigned_64 (Time_Usec);
Frame.Cur_Depth := Count;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
MAT.Frames.Insert (Frame => Client.Frames,
Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
end MAT.Events.Probes;
|
Remove the Read_Headers procedure
|
Remove the Read_Headers procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
a6961727e90edb96d2205034323d15c9d1149996
|
src/base/commands/util-commands-drivers.adb
|
src/base/commands/util-commands-drivers.adb
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Ada.Text_IO; use Ada.Text_IO;
package body Util.Commands.Drivers is
use Ada.Strings.Unbounded;
-- The logger
Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name);
-- ------------------------------
-- Get the description associated with the command.
-- ------------------------------
function Get_Description (Command : in Command_Type) return String is
begin
return To_String (Command.Description);
end Get_Description;
-- ------------------------------
-- Get the name used to register the command.
-- ------------------------------
function Get_Name (Command : in Command_Type) return String is
begin
return To_String (Command.Name);
end Get_Name;
-- ------------------------------
-- Write the command usage.
-- ------------------------------
procedure Usage (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
Config : Config_Type;
begin
Command_Type'Class (Command).Setup (Config, Context);
Config_Parser.Usage (Name, Config);
end Usage;
-- ------------------------------
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
-- ------------------------------
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String) is
begin
Command.Driver.Log (Level, Name, Message);
end Log;
-- ------------------------------
-- Execute the help command with the arguments.
-- Print the help for every registered command.
-- ------------------------------
overriding
procedure Execute (Command : in out Help_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
procedure Compute_Size (Position : in Command_Sets.Cursor);
procedure Print (Position : in Command_Sets.Cursor);
Column : Ada.Text_IO.Positive_Count := 1;
procedure Compute_Size (Position : in Command_Sets.Cursor) is
Cmd : constant Command_Access := Command_Sets.Element (Position);
Len : constant Natural := Length (Cmd.Name);
begin
if Natural (Column) < Len then
Column := Ada.Text_IO.Positive_Count (Len);
end if;
end Compute_Size;
procedure Print (Position : in Command_Sets.Cursor) is
Cmd : constant Command_Access := Command_Sets.Element (Position);
begin
Put (" ");
Put (To_String (Cmd.Name));
if Length (Cmd.Description) > 0 then
Set_Col (Column + 7);
Put (To_String (Cmd.Description));
end if;
New_Line;
end Print;
begin
Logs.Debug ("Execute command {0}", Name);
if Args.Get_Count = 0 then
Usage (Command.Driver.all, Args, Context);
New_Line;
Put ("Type '");
Put (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 => Compute_Size'Access);
Command.Driver.List.Iterate (Process => Print'Access);
else
declare
Cmd_Name : constant String := Args.Get_Argument (1);
Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name);
begin
if Target_Cmd = null then
Logs.Error ("Unknown command '{0}'", Cmd_Name);
raise Not_Found;
else
Target_Cmd.Help (Cmd_Name, Context);
end if;
end;
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Command : in out Help_Command_Type;
Name : in String;
Context : in out Context_Type) is
begin
null;
end Help;
-- ------------------------------
-- Report the command usage.
-- ------------------------------
procedure Usage (Driver : in Driver_Type;
Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "") is
begin
Put_Line (To_String (Driver.Desc));
New_Line;
if Name'Length > 0 then
declare
Command : constant Command_Access := Driver.Find_Command (Name);
begin
if Command /= null then
Command.Usage (Name, Context);
else
Put ("Invalid command");
end if;
end;
else
Put ("Usage: ");
Put (Args.Get_Command_Name);
Put (" ");
Put_Line (To_String (Driver.Usage));
end if;
end Usage;
-- ------------------------------
-- Set the driver description printed in the usage.
-- ------------------------------
procedure Set_Description (Driver : in out Driver_Type;
Description : in String) is
begin
Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description);
end Set_Description;
-- ------------------------------
-- Set the driver usage printed in the usage.
-- ------------------------------
procedure Set_Usage (Driver : in out Driver_Type;
Usage : in String) is
begin
Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage);
end Set_Usage;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access) is
begin
Command.Name := To_Unbounded_String (Name);
Command.Driver := Driver'Unchecked_Access;
Driver.List.Include (Command);
end Add_Command;
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Command : in Command_Access) is
begin
Command.Name := To_Unbounded_String (Name);
Command.Description := To_Unbounded_String (Description);
Add_Command (Driver, Name, Command);
end Add_Command;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Handler : in Command_Handler) is
Command : constant Command_Access
:= new Handler_Command_Type '(Driver => Driver'Unchecked_Access,
Description => To_Unbounded_String (Description),
Name => To_Unbounded_String (Name),
Handler => Handler);
begin
Driver.List.Include (Command);
end Add_Command;
-- ------------------------------
-- Find the command having the given name.
-- Returns null if the command was not found.
-- ------------------------------
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access is
Cmd : aliased Help_Command_Type;
Pos : Command_Sets.Cursor;
begin
Cmd.Name := To_Unbounded_String (Name);
Pos := Driver.List.Find (Cmd'Unchecked_Access);
if Command_Sets.Has_Element (Pos) then
return Command_Sets.Element (Pos);
else
return null;
end if;
end Find_Command;
-- ------------------------------
-- Execute the command registered under the given name.
-- ------------------------------
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
procedure Execute (Cmd_Args : in Argument_List'Class);
Command : constant Command_Access := Driver.Find_Command (Name);
procedure Execute (Cmd_Args : in Argument_List'Class) is
begin
Command.Execute (Name, Cmd_Args, Context);
end Execute;
begin
if Command /= null then
declare
Config : Config_Type;
begin
Command.Setup (Config, Context);
Config_Parser.Execute (Config, Args, Execute'Access);
end;
else
Logs.Error ("Unkown command '{0}'", Name);
raise Not_Found;
end if;
end Execute;
-- ------------------------------
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- ------------------------------
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String) is
pragma Unreferenced (Driver);
begin
Logs.Print (Level, "{0}: {1}", Name, Message);
end Log;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Command : in out Handler_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
begin
Command.Handler (Name, Args, Context);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Handler_Command_Type;
Name : in String;
Context : in out Context_Type) is
begin
null;
end Help;
end Util.Commands.Drivers;
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Ada.Text_IO; use Ada.Text_IO;
package body Util.Commands.Drivers is
use Ada.Strings.Unbounded;
-- The logger
Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name);
function "-" (Message : in String) return String is (Translate (Message)) with Inline;
-- ------------------------------
-- Get the description associated with the command.
-- ------------------------------
function Get_Description (Command : in Command_Type) return String is
begin
return To_String (Command.Description);
end Get_Description;
-- ------------------------------
-- Get the name used to register the command.
-- ------------------------------
function Get_Name (Command : in Command_Type) return String is
begin
return To_String (Command.Name);
end Get_Name;
-- ------------------------------
-- Write the command usage.
-- ------------------------------
procedure Usage (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
Config : Config_Type;
begin
Command_Type'Class (Command).Setup (Config, Context);
Config_Parser.Usage (Name, Config);
end Usage;
-- ------------------------------
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
-- ------------------------------
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String) is
begin
Command.Driver.Log (Level, Name, Message);
end Log;
-- ------------------------------
-- Execute the help command with the arguments.
-- Print the help for every registered command.
-- ------------------------------
overriding
procedure Execute (Command : in out Help_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
procedure Compute_Size (Position : in Command_Sets.Cursor);
procedure Print (Position : in Command_Sets.Cursor);
Column : Ada.Text_IO.Positive_Count := 1;
procedure Compute_Size (Position : in Command_Sets.Cursor) is
Cmd : constant Command_Access := Command_Sets.Element (Position);
Len : constant Natural := Length (Cmd.Name);
begin
if Natural (Column) < Len then
Column := Ada.Text_IO.Positive_Count (Len);
end if;
end Compute_Size;
procedure Print (Position : in Command_Sets.Cursor) is
Cmd : constant Command_Access := Command_Sets.Element (Position);
begin
Put (" ");
Put (To_String (Cmd.Name));
if Length (Cmd.Description) > 0 then
Set_Col (Column + 7);
Put (To_String (Cmd.Description));
end if;
New_Line;
end Print;
begin
Logs.Debug ("Execute command {0}", Name);
if Args.Get_Count = 0 then
Usage (Command.Driver.all, Args, Context);
New_Line;
Put ("Type '");
Put (Driver_Name);
Put_Line (" help {command}' for help on a specific command.");
New_Line;
Put_Line (-("Available subcommands:"));
Command.Driver.List.Iterate (Process => Compute_Size'Access);
Command.Driver.List.Iterate (Process => Print'Access);
else
declare
Cmd_Name : constant String := Args.Get_Argument (1);
Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name);
begin
if Target_Cmd = null then
Logs.Error (-("Unknown command '{0}'"), Cmd_Name);
raise Not_Found;
else
Target_Cmd.Help (Cmd_Name, Context);
end if;
end;
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Command : in out Help_Command_Type;
Name : in String;
Context : in out Context_Type) is
begin
null;
end Help;
-- ------------------------------
-- Report the command usage.
-- ------------------------------
procedure Usage (Driver : in Driver_Type;
Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "") is
begin
Put_Line (To_String (Driver.Desc));
New_Line;
if Name'Length > 0 then
declare
Command : constant Command_Access := Driver.Find_Command (Name);
begin
if Command /= null then
Command.Usage (Name, Context);
else
Put (-("Invalid command"));
end if;
end;
else
Put (-("Usage: "));
Put (Args.Get_Command_Name);
Put (" ");
Put_Line (To_String (Driver.Usage));
end if;
end Usage;
-- ------------------------------
-- Set the driver description printed in the usage.
-- ------------------------------
procedure Set_Description (Driver : in out Driver_Type;
Description : in String) is
begin
Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description);
end Set_Description;
-- ------------------------------
-- Set the driver usage printed in the usage.
-- ------------------------------
procedure Set_Usage (Driver : in out Driver_Type;
Usage : in String) is
begin
Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage);
end Set_Usage;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access) is
begin
Command.Name := To_Unbounded_String (Name);
Command.Driver := Driver'Unchecked_Access;
Driver.List.Include (Command);
end Add_Command;
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Command : in Command_Access) is
begin
Command.Name := To_Unbounded_String (Name);
Command.Description := To_Unbounded_String (Description);
Add_Command (Driver, Name, Command);
end Add_Command;
-- ------------------------------
-- Register the command under the given name.
-- ------------------------------
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Handler : in Command_Handler) is
Command : constant Command_Access
:= new Handler_Command_Type '(Driver => Driver'Unchecked_Access,
Description => To_Unbounded_String (Description),
Name => To_Unbounded_String (Name),
Handler => Handler);
begin
Driver.List.Include (Command);
end Add_Command;
-- ------------------------------
-- Find the command having the given name.
-- Returns null if the command was not found.
-- ------------------------------
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access is
Cmd : aliased Help_Command_Type;
Pos : Command_Sets.Cursor;
begin
Cmd.Name := To_Unbounded_String (Name);
Pos := Driver.List.Find (Cmd'Unchecked_Access);
if Command_Sets.Has_Element (Pos) then
return Command_Sets.Element (Pos);
else
return null;
end if;
end Find_Command;
-- ------------------------------
-- Execute the command registered under the given name.
-- ------------------------------
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
procedure Execute (Cmd_Args : in Argument_List'Class);
Command : constant Command_Access := Driver.Find_Command (Name);
procedure Execute (Cmd_Args : in Argument_List'Class) is
begin
Command.Execute (Name, Cmd_Args, Context);
end Execute;
begin
if Command /= null then
declare
Config : Config_Type;
begin
Command.Setup (Config, Context);
Config_Parser.Execute (Config, Args, Execute'Access);
end;
else
Logs.Error (-("Unkown command '{0}'"), Name);
raise Not_Found;
end if;
end Execute;
-- ------------------------------
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- ------------------------------
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String) is
pragma Unreferenced (Driver);
begin
Logs.Print (Level, "{0}: {1}", Name, Message);
end Log;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Command : in out Handler_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
begin
Command.Handler (Name, Args, Context);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Handler_Command_Type;
Name : in String;
Context : in out Context_Type) is
begin
null;
end Help;
end Util.Commands.Drivers;
|
Use the Translate function for every message that can be reported to the user
|
Use the Translate function for every message that can be reported to the user
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
69b717346452dab9895b5a53bddcda3bf25a8f3e
|
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");
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 Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
declare
Handler : constant Message_Handler := Handler_Maps.Element (Pos);
begin
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Msg);
end;
end if;
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);
procedure Read_Attributes (Key : in String;
Element : in out Message_Handler) is
begin
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
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);
begin
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
end if;
end loop;
end;
end loop;
end Read_Attributes;
begin
Log.Debug ("Read event definition {0}", Name);
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attributes'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;
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");
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 Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
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
declare
Handler : constant Message_Handler := Handler_Maps.Element (Pos);
begin
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Msg);
end;
end if;
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);
begin
Log.Debug ("Read event definition {0}", Name);
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);
end if;
end loop;
end Read_Attribute;
begin
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attribute'Access);
end if;
end;
end loop;
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;
end Read_Headers;
end MAT.Readers;
|
Fix reading the event description in the header section
|
Fix reading the event description in the header section
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
0e826630ab0fe0372850938713d2b1467b0d5345
|
src/gen-artifacts-docs-googlecode.adb
|
src/gen-artifacts-docs-googlecode.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Artifacts.Docs.Googlecode is
-- ------------------------------
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
-- ------------------------------
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki";
end Get_Document_Name;
-- ------------------------------
-- Start a new document.
-- ------------------------------
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is
begin
Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end Start_Document;
-- ------------------------------
-- Write a line in the target document formatting the line if necessary.
-- ------------------------------
overriding
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is
begin
if Line.Kind = L_LIST then
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
elsif Line.Kind = L_LIST_ITEM then
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
else
if Formatter.Need_Newline then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
Ada.Text_IO.Put_Line (File, Line.Content);
end if;
end Write_Line;
end Gen.Artifacts.Docs.Googlecode;
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Artifacts.Docs.Googlecode is
-- ------------------------------
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
-- ------------------------------
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki";
end Get_Document_Name;
-- ------------------------------
-- Start a new document.
-- ------------------------------
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is
begin
Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end Start_Document;
-- ------------------------------
-- Write a line in the target document formatting the line if necessary.
-- ------------------------------
overriding
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is
begin
if Line.Kind = L_LIST then
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
elsif Line.Kind = L_LIST_ITEM then
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
else
if Formatter.Need_Newline then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
Ada.Text_IO.Put_Line (File, Line.Content);
end if;
end Write_Line;
-- ------------------------------
-- Finish the document.
-- ------------------------------
overriding
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String) is
begin
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put_Line (File, "----");
Ada.Text_IO.Put_Line (File,
"[https://github.com/stcarrez/dynamo Generated by Dynamo] from _"
& Source & "_");
end Finish_Document;
end Gen.Artifacts.Docs.Googlecode;
|
Implement the Finish_Document procedure
|
Implement the Finish_Document procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
7ecf5741c204f883122a9d484a16759bc1e3060a
|
regtests/ado-schemas-tests.ads
|
regtests/ado-schemas-tests.ads
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 2009, 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Schemas.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test reading the entity cache and the Find_Entity_Type operation
procedure Test_Find_Entity_Type (T : in out Test);
-- Test calling Find_Entity_Type with an invalid table.
procedure Test_Find_Entity_Type_Error (T : in out Test);
-- Test the Load_Schema operation and check the result schema.
procedure Test_Load_Schema (T : in out Test);
-- Test the Table_Cursor operations and check the result schema.
procedure Test_Table_Iterator (T : in out Test);
-- Test the Table_Cursor operations on an empty schema.
procedure Test_Empty_Schema (T : in out Test);
end ADO.Schemas.Tests;
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 2009, 2010, 2011, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Schemas.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test reading the entity cache and the Find_Entity_Type operation
procedure Test_Find_Entity_Type (T : in out Test);
-- Test calling Find_Entity_Type with an invalid table.
procedure Test_Find_Entity_Type_Error (T : in out Test);
-- Test the Load_Schema operation and check the result schema.
procedure Test_Load_Schema (T : in out Test);
-- Test the Table_Cursor operations and check the result schema.
procedure Test_Table_Iterator (T : in out Test);
-- Test the Table_Cursor operations on an empty schema.
procedure Test_Empty_Schema (T : in out Test);
-- Test the creation of database.
procedure Test_Create_Schema (T : in out Test);
end ADO.Schemas.Tests;
|
Declare the Test_Create_Schema procedure
|
Declare the Test_Create_Schema procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
6551e719ce3256c81335d086d76553fb7aac0e2d
|
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_Ptr;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
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);
-- Memory allocation objects are stored in an AVL tree sorted
-- on the memory slot address.
--
subtype Allocation_Map is Allocation_Maps.Map;
--
-- subtype Allocation_Ref is Allocation_AVL.Iterator;
-- -- Type representing a reference to a memory allocation slot.
--
-- use Allocation_AVL;
-- package Allocation_Ref_Containers is new BC.Containers (Allocation_Ref);
-- package Allocation_Ref_Trees is new Allocation_Ref_Containers.Trees;
-- package Allocation_Ref_AVL is
-- new Allocation_Ref_Trees.AVL (Key => Target_Addr,
-- Storage => Global_Heap.Storage);
-- -- Tree of references to memory allocation objects.
--
-- subtype Allocation_Ref_Map is Allocation_Ref_AVL.AVL_Tree;
-- subtype Allocation_Ref_Ref is Allocation_Ref_AVL.Iterator;
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_Ptr;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
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);
-- Memory allocation objects are stored in an AVL tree sorted
-- on the memory slot address.
--
subtype Allocation_Map is Allocation_Maps.Map;
subtype Allocation_Cursor is Allocation_Maps.Cursor;
--
-- subtype Allocation_Ref is Allocation_AVL.Iterator;
-- -- Type representing a reference to a memory allocation slot.
--
-- use Allocation_AVL;
-- package Allocation_Ref_Containers is new BC.Containers (Allocation_Ref);
-- package Allocation_Ref_Trees is new Allocation_Ref_Containers.Trees;
-- package Allocation_Ref_AVL is
-- new Allocation_Ref_Trees.AVL (Key => Target_Addr,
-- Storage => Global_Heap.Storage);
-- -- Tree of references to memory allocation objects.
--
-- subtype Allocation_Ref_Map is Allocation_Ref_AVL.AVL_Tree;
-- subtype Allocation_Ref_Ref is Allocation_Ref_AVL.Iterator;
private
end MAT.Memory;
|
Define Allocation_Cursor
|
Define Allocation_Cursor
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
97e1b892d07ca1078001e5a83008c196c5821b50
|
regtests/util-beans-objects-datasets-tests.adb
|
regtests/util-beans-objects-datasets-tests.adb
|
-----------------------------------------------------------------------
-- util-beans-objects-datasets-tests -- Unit tests for dataset beans
-- Copyright (C) 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Util.Beans.Objects.Datasets.Tests is
package Caller is new Util.Test_Caller (Test, "Objects.Datasets");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Beans.Objects.Datasets",
Test_Fill_Dataset'Access);
end Add_Tests;
-- Test the creation, initialization and retrieval of dataset content.
procedure Test_Fill_Dataset (T : in out Test) is
Set : Dataset;
procedure Fill (Row : in out Object_Array) is
begin
Row (Row'First) := To_Object (String '("john"));
Row (Row'First + 1) := To_Object (String '("[email protected]"));
Row (Row'First + 2) := To_Object (Set.Get_Count);
end Fill;
begin
Set.Add_Column ("name");
Set.Add_Column ("email");
Set.Add_Column ("age");
for I in 1 .. 100 loop
Set.Append (Fill'Access);
end loop;
Util.Tests.Assert_Equals (T, 100, Set.Get_Count, "Invalid number of rows");
for I in 1 .. 100 loop
Set.Set_Row_Index (I);
declare
R : constant Object := Set.Get_Row;
begin
T.Assert (not Is_Null (R), "Row is null");
Util.Tests.Assert_Equals (T, "john", To_String (Get_Value (R, "name")),
"Invalid 'name' attribute");
Util.Tests.Assert_Equals (T, I, To_Integer (Get_Value (R, "age")),
"Invalid 'age' attribute");
end;
end loop;
end Test_Fill_Dataset;
end Util.Beans.Objects.Datasets.Tests;
|
-----------------------------------------------------------------------
-- util-beans-objects-datasets-tests -- Unit tests for dataset beans
-- Copyright (C) 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Util.Beans.Objects.Datasets.Tests is
package Caller is new Util.Test_Caller (Test, "Objects.Datasets");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Beans.Objects.Datasets",
Test_Fill_Dataset'Access);
end Add_Tests;
-- Test the creation, initialization and retrieval of dataset content.
procedure Test_Fill_Dataset (T : in out Test) is
procedure Fill (Row : in out Object_Array);
Set : Dataset;
procedure Fill (Row : in out Object_Array) is
begin
Row (Row'First) := To_Object (String '("john"));
Row (Row'First + 1) := To_Object (String '("[email protected]"));
Row (Row'First + 2) := To_Object (Set.Get_Count);
end Fill;
begin
Set.Add_Column ("name");
Set.Add_Column ("email");
Set.Add_Column ("age");
for I in 1 .. 100 loop
Set.Append (Fill'Access);
end loop;
Util.Tests.Assert_Equals (T, 100, Set.Get_Count, "Invalid number of rows");
for I in 1 .. 100 loop
Set.Set_Row_Index (I);
declare
R : constant Object := Set.Get_Row;
begin
T.Assert (not Is_Null (R), "Row is null");
Util.Tests.Assert_Equals (T, "john", To_String (Get_Value (R, "name")),
"Invalid 'name' attribute");
Util.Tests.Assert_Equals (T, I, To_Integer (Get_Value (R, "age")),
"Invalid 'age' attribute");
end;
end loop;
end Test_Fill_Dataset;
end Util.Beans.Objects.Datasets.Tests;
|
Declare the Fill internal procedure
|
Declare the Fill internal procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
03bde3cb05db7e5307e30fa91ebad1af92a3e422
|
src/asf-servlets-faces-mappers.adb
|
src/asf-servlets-faces-mappers.adb
|
-----------------------------------------------------------------------
-- asf-servlets-faces-mappers -- Read faces specific configuration files
-- Copyright (C) 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Servlet.Core;
with ASF.Routes;
package body ASF.Servlets.Faces.Mappers is
use type ASF.Routes.Route_Type_Access;
use type Servlet.Core.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access is
Disp : constant Servlet.Core.Request_Dispatcher := Container.Get_Request_Dispatcher (View);
Serv : constant Servlet_Access := Servlet.Core.Get_Servlet (Disp);
begin
if Serv = null then
raise Util.Serialize.Mappers.Field_Error with "No servlet mapped to view " & View;
end if;
return Serv; -- Servlet.Routes.Servlets.Servlet_Route_Type'Class (Route.all).Servlet;
end Find_Servlet;
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the URL_MAPPING, URL_PATTERN, VIEW_ID field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Field is
when URL_PATTERN =>
N.URL_Pattern := Value;
when VIEW_ID =>
N.View_Id := Value;
when URL_MAPPING =>
declare
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref);
View : constant String := To_String (N.View_Id);
Servlet : constant ASF.Servlets.Servlet_Access := Find_Servlet (N.Handler, View);
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
To : ASF.Routes.Faces_Route_Type_Access;
begin
if Route.Is_Null then
To := new ASF.Routes.Faces_Route_Type;
To.View := Ada.Strings.Unbounded.To_Unbounded_String (View);
To.Servlet := Servlet;
Route := ASF.Routes.Route_Type_Refs.Create (To.all'Access);
end if;
end Insert;
begin
N.Handler.Add_Route (Pattern => To_String (N.URL_Pattern),
ELContext => N.Context.all,
Process => Insert'Access);
end;
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>url-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Mapper.Add_Mapping ("faces-config", SMapper'Access);
Mapper.Add_Mapping ("module", SMapper'Access);
Mapper.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Mapper, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("url-mapping", URL_MAPPING);
SMapper.Add_Mapping ("url-mapping/pattern", URL_PATTERN);
SMapper.Add_Mapping ("url-mapping/view-id", VIEW_ID);
end ASF.Servlets.Faces.Mappers;
|
-----------------------------------------------------------------------
-- asf-servlets-faces-mappers -- Read faces specific configuration files
-- Copyright (C) 2015, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Servlet.Core;
with ASF.Routes;
package body ASF.Servlets.Faces.Mappers is
use type Servlet.Core.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access is
Disp : constant Servlet.Core.Request_Dispatcher := Container.Get_Request_Dispatcher (View);
Serv : constant Servlet_Access := Servlet.Core.Get_Servlet (Disp);
begin
if Serv = null then
raise Util.Serialize.Mappers.Field_Error with "No servlet mapped to view " & View;
end if;
return Serv;
end Find_Servlet;
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the URL_MAPPING, URL_PATTERN, VIEW_ID field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Field is
when URL_PATTERN =>
N.URL_Pattern := Value;
when VIEW_ID =>
N.View_Id := Value;
when URL_MAPPING =>
declare
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref);
View : constant String := To_String (N.View_Id);
Servlet : constant ASF.Servlets.Servlet_Access := Find_Servlet (N.Handler, View);
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
To : ASF.Routes.Faces_Route_Type_Access;
begin
if Route.Is_Null then
To := new ASF.Routes.Faces_Route_Type;
To.View := Ada.Strings.Unbounded.To_Unbounded_String (View);
To.Servlet := Servlet;
Route := ASF.Routes.Route_Type_Refs.Create (To.all'Access);
end if;
end Insert;
begin
N.Handler.Add_Route (Pattern => To_String (N.URL_Pattern),
ELContext => N.Context.all,
Process => Insert'Access);
end;
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>url-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Mapper.Add_Mapping ("faces-config", SMapper'Access);
Mapper.Add_Mapping ("module", SMapper'Access);
Mapper.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Mapper, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("url-mapping", URL_MAPPING);
SMapper.Add_Mapping ("url-mapping/pattern", URL_PATTERN);
SMapper.Add_Mapping ("url-mapping/view-id", VIEW_ID);
end ASF.Servlets.Faces.Mappers;
|
Remove unused use clauses
|
Remove unused use clauses
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
728aeb9c0fcec21921b304bc2fbefc3967be6390
|
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, 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;
|
-----------------------------------------------------------------------
-- util-beans-basic-lists -- List bean given access to a vector
-- Copyright (C) 2011, 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.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;
|
Update the header
|
Update the header
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
6c0c621d682e85f088088dad4987a66a0ff20a4b
|
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES 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 ("compute", 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;
|
-----------------------------------------------------------------------
-- 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 Util.Log.Loggers;
with Volume;
procedure Asf_Volume_Server is
CONTEXT_PATH : constant String := "/volume";
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;
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
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", 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);
Log.Info ("Connect you browser to: http://localhost:8080/volume/compute.html");
WS.Start;
delay 600.0;
end Asf_Volume_Server;
|
Add a log to tell the main URL to look at after the server is started
|
Add a log to tell the main URL to look at after the server is started
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
08822654adfb34fcb44e3061c85e294731657874
|
src/util-beans-objects-vectors.adb
|
src/util-beans-objects-vectors.adb
|
-----------------------------------------------------------------------
-- util-beans-vectors -- Object vectors
-- Copyright (C) 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Vectors 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 Vector_Bean;
Name : in String) return Object is
begin
return Null_Object;
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 Vector_Bean;
Name : in String;
Value : in Object) is
begin
null;
end Set_Value;
-- Create an object that contains a <tt>Vector_Bean</tt> instance.
function Create return Object is
M : constant access Vector_Bean'Class := new Vector_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
end Util.Beans.Objects.Vectors;
|
-----------------------------------------------------------------------
-- util-beans-vectors -- Object vectors
-- Copyright (C) 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Vectors 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 Vector_Bean;
Name : in String) return Object is
begin
if Name = "count" then
return To_Object (Natural (From.Length));
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Vector_Bean) return Natural is
begin
return Natural (From.Length);
end Get_Count;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
overriding
function Get_Row (From : in Vector_Bean;
Position : in Natural) return Util.Beans.Objects.Object is
begin
return From.Element (Position);
end Get_Row;
-- -----------------------
-- Create an object that contains a <tt>Vector_Bean</tt> instance.
-- -----------------------
function Create return Object is
M : constant access Vector_Bean'Class := new Vector_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
end Util.Beans.Objects.Vectors;
|
Implement the Vector_Bean operations for the Array_Bean interface
|
Implement the Vector_Bean operations for the Array_Bean interface
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1e746a8f14759a85d45a1476f6704ccf75cedd35
|
src/util-streams-texts.ads
|
src/util-streams-texts.ads
|
-----------------------------------------------------------------------
-- Util.Streams.Files -- File Stream utilities
-- Copyright (C) 2010, 2011, 2012, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Streams.Buffered;
with Util.Texts.Transforms;
with Ada.Characters.Handling;
with Ada.Wide_Wide_Characters.Handling;
with Ada.Calendar;
with GNAT.Calendar.Time_IO;
package Util.Streams.Texts is
-- -----------------------
-- Print stream
-- -----------------------
-- The <b>Print_Stream</b> is an output stream which provides helper methods
-- for writing text streams.
type Print_Stream is new Buffered.Buffered_Stream with private;
type Print_Stream_Access is access all Print_Stream'Class;
procedure Initialize (Stream : in out Print_Stream;
To : in Output_Stream_Access);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Integer);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer);
-- Write a string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a date on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date);
-- Get the output stream content as a string.
function To_String (Stream : in Buffered.Buffered_Stream) return String;
-- Write a character on the stream.
procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class;
Item : in Character);
-- Write a character on the stream.
procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class;
Item : in Wide_Wide_Character);
package TR is
new Util.Texts.Transforms (Stream => Buffered.Buffered_Stream'Class,
Char => Character,
Input => String,
Put => Write_Char,
To_Upper => Ada.Characters.Handling.To_Upper,
To_Lower => Ada.Characters.Handling.To_Lower);
package WTR is
new Util.Texts.Transforms (Stream => Buffered.Buffered_Stream'Class,
Char => Wide_Wide_Character,
Input => Wide_Wide_String,
Put => Write_Char,
To_Upper => Ada.Wide_Wide_Characters.Handling.To_Upper,
To_Lower => Ada.Wide_Wide_Characters.Handling.To_Lower);
-- -----------------------
-- Reader stream
-- -----------------------
-- The <b>Reader_Stream</b> is an input stream which provides helper methods
-- for reading text streams.
type Reader_Stream is new Buffered.Buffered_Stream with private;
type Reader_Stream_Access is access all Reader_Stream'Class;
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
procedure Initialize (Stream : in out Reader_Stream;
From : in Input_Stream_Access);
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False);
private
type Print_Stream is new Buffered.Buffered_Stream with null record;
type Reader_Stream is new Buffered.Buffered_Stream with null record;
end Util.Streams.Texts;
|
-----------------------------------------------------------------------
-- Util.Streams.Files -- File Stream utilities
-- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Streams.Buffered;
with Util.Texts.Transforms;
with Ada.Characters.Handling;
with Ada.Wide_Wide_Characters.Handling;
with Ada.Calendar;
with GNAT.Calendar.Time_IO;
package Util.Streams.Texts is
-- -----------------------
-- Print stream
-- -----------------------
-- The <b>Print_Stream</b> is an output stream which provides helper methods
-- for writing text streams.
type Print_Stream is new Buffered.Buffered_Stream with private;
type Print_Stream_Access is access all Print_Stream'Class;
procedure Initialize (Stream : in out Print_Stream;
To : in Output_Stream_Access);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Integer);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer);
-- Write a string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a date on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date);
-- Get the output stream content as a string.
function To_String (Stream : in Buffered.Buffered_Stream'Class) return String;
-- Write a character on the stream.
procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class;
Item : in Character);
-- Write a character on the stream.
procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class;
Item : in Wide_Wide_Character);
package TR is
new Util.Texts.Transforms (Stream => Buffered.Buffered_Stream'Class,
Char => Character,
Input => String,
Put => Write_Char,
To_Upper => Ada.Characters.Handling.To_Upper,
To_Lower => Ada.Characters.Handling.To_Lower);
package WTR is
new Util.Texts.Transforms (Stream => Buffered.Buffered_Stream'Class,
Char => Wide_Wide_Character,
Input => Wide_Wide_String,
Put => Write_Char,
To_Upper => Ada.Wide_Wide_Characters.Handling.To_Upper,
To_Lower => Ada.Wide_Wide_Characters.Handling.To_Lower);
-- -----------------------
-- Reader stream
-- -----------------------
-- The <b>Reader_Stream</b> is an input stream which provides helper methods
-- for reading text streams.
type Reader_Stream is new Buffered.Buffered_Stream with private;
type Reader_Stream_Access is access all Reader_Stream'Class;
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
procedure Initialize (Stream : in out Reader_Stream;
From : in Input_Stream_Access);
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False);
private
type Print_Stream is new Buffered.Buffered_Stream with null record;
type Reader_Stream is new Buffered.Buffered_Stream with null record;
end Util.Streams.Texts;
|
Change To_String function to accept class wide buffer stream objects
|
Change To_String function to accept class wide buffer stream objects
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b21ac6234d61b82144e25617e8e96407f7167b81
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Invitation_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "inviter" then
return From.Inviter.Get_Value ("name");
else
return AWA.Workspaces.Models.Invitation_Bean (From).Get_Value (Name);
end if;
end Get_Value;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean,
Inviter => Bean.Inviter);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key));
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Send_Invitation (Bean);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" then
return Util.Beans.Objects.To_Object (Value => From.Members_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Master_Session := Into.Module.Get_Master_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
AWA.Workspaces.Modules.Get_Workspace (Session, Ctx, WS);
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id);
Count_Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
-----------------------------------------------------------------------
-- 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;
|
Implement the Create_Member_Bean and operations for the Member_Bean type
|
Implement the Create_Member_Bean and operations for the Member_Bean type
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b568b038549cf8e9220305e410f08d66c2d2feaf
|
src/util-concurrent-fifos.adb
|
src/util-concurrent-fifos.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : constant Element_Array_Access := new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
-----------------------------------------------------------------------
-- Util.Concurrent.Fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : constant Element_Array_Access
:= new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
Fix compilation style warning
|
Fix compilation style warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f3c4715620280f0e0c99b5f7ca866b2d08360b16
|
awa/plugins/awa-blogs/regtests/awa-blogs-modules-tests.adb
|
awa/plugins/awa-blogs/regtests/awa-blogs-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Blogs.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Blogs.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Blogs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post",
Test_Create_Post'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a blog
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Title => "My blog",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
end Test_Create_Blog;
-- ------------------------------
-- Test creating and updating of a blog post
-- ------------------------------
procedure Test_Create_Post (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Post_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Title => "My blog post",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
for I in 1 .. 5 loop
Manager.Create_Post (Blog_Id => Blog_Id,
Title => "Testing blog title",
URI => "testing-blog-title",
Text => "The blog content",
Comment => False,
Status => AWA.Blogs.Models.POST_DRAFT,
Result => Post_Id);
T.Assert (Post_Id > 0, "Invalid post identifier");
Manager.Update_Post (Post_Id => Post_Id,
Title => "New blog post title",
URI => "testing-blog-title",
Text => "The new post content",
Comment => True,
Status => AWA.Blogs.Models.POST_DRAFT);
-- Keep the last post in the database.
exit when I = 5;
Manager.Delete_Post (Post_Id => Post_Id);
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Update_Post (Post_Id => Post_Id,
Title => "Something",
Text => "Content",
URI => "testing-blog-title",
Comment => True,
Status => AWA.Blogs.Models.POST_DRAFT);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Delete_Post (Post_Id => Post_Id);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
end loop;
end Test_Create_Post;
end AWA.Blogs.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Blogs.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Blogs.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Blogs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post",
Test_Create_Post'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a blog
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Title => "My blog",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
end Test_Create_Blog;
-- ------------------------------
-- Test creating and updating of a blog post
-- ------------------------------
procedure Test_Create_Post (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Post_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Title => "My blog post",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
for I in 1 .. 5 loop
Manager.Create_Post (Blog_Id => Blog_Id,
Title => "Testing blog title",
URI => "testing-blog-title",
Text => "The blog content",
Comment => False,
Status => AWA.Blogs.Models.POST_DRAFT,
Result => Post_Id);
T.Assert (Post_Id > 0, "Invalid post identifier");
Manager.Update_Post (Post_Id => Post_Id,
Title => "New blog post title",
URI => "testing-blog-title",
Text => "The new post content",
Publish_Date => ADO.Nullable_Time '(Is_Null => True, others => <>),
Comment => True,
Status => AWA.Blogs.Models.POST_DRAFT);
-- Keep the last post in the database.
exit when I = 5;
Manager.Delete_Post (Post_Id => Post_Id);
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Update_Post (Post_Id => Post_Id,
Title => "Something",
Text => "Content",
URI => "testing-blog-title",
Publish_Date => ADO.Nullable_Time '(Is_Null => True, others => <>),
Comment => True,
Status => AWA.Blogs.Models.POST_DRAFT);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Delete_Post (Post_Id => Post_Id);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
end loop;
end Test_Create_Post;
end AWA.Blogs.Modules.Tests;
|
Update the unit test for publication date
|
Update the unit test for publication date
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f6c147f328635a849c5f746dbe6d019a4b1a7378
|
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
|
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Wikis.Modules.Tests is
use ASF.Tests;
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Wikis.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space",
Test_Create_Wiki_Space'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page",
Test_Create_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content",
Test_Create_Wiki_Content'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Wiki_Page",
Test_Wiki_Page'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Create_Wiki_Space (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
W2 : AWA.Wikis.Models.Wiki_Space_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Assert (W.Is_Inserted, "The new wiki space was not created");
W.Set_Name ("Test wiki space update");
W.Set_Is_Public (True);
T.Manager.Save_Wiki_Space (W);
T.Manager.Load_Wiki_Space (Wiki => W2,
Id => W.Get_Id);
Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
"Invalid wiki space name");
end Test_Create_Wiki_Space;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
P.Set_Name ("Private");
P.Set_Title ("The page title");
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
C := AWA.Wikis.Models.Null_Wiki_Content;
P := AWA.Wikis.Models.Null_Wiki_Page;
P.Set_Name ("Public");
P.Set_Title ("The page title (public)");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
T.Assert (P.Get_Is_Public, "The new wiki page is not public");
end Test_Create_Wiki_Page;
-- ------------------------------
-- Test creation of a wiki page content.
-- ------------------------------
procedure Test_Create_Wiki_Content (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Wiki_Id := W.Get_Id;
P.Set_Name ("PrivatePage");
P.Set_Title ("The page title");
P.Set_Is_Public (False);
T.Manager.Create_Wiki_Page (W, P, C);
T.Private_Id := P.Get_Id;
C := AWA.Wikis.Models.Null_Wiki_Content;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
P := AWA.Wikis.Models.Null_Wiki_Page;
C := AWA.Wikis.Models.Null_Wiki_Content;
P.Set_Name ("PublicPage");
P.Set_Title ("The public page title");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Public_Id := P.Get_Id;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph" & ASCII.LF
& "[Link](http://mylink.com)" & ASCII.LF
& "[Image](my-image.png)");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
end Test_Create_Wiki_Content;
-- ------------------------------
-- Test getting the wiki page as well as info, history pages.
-- ------------------------------
procedure Test_Wiki_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PublicPage", "wiki-public-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident,
"wiki-public-info-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage info)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/history/" & Ident & "/" & Pub_Ident,
"wiki-public-history-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage history)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
Request.Remove_Attribute ("wikiView");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PrivatePage", "wiki-private-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PrivatePage)");
Assert_Matches (T, ".*Protected Wiki Page.*", Reply, "Invalid PrivatePage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent", "wiki-list-recent-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent/grid", "wiki-list-grid-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent/grid)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular", "wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular/grid", "wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular/grid)");
end Test_Wiki_Page;
end AWA.Wikis.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Wikis.Modules.Tests is
use ASF.Tests;
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Wikis.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space",
Test_Create_Wiki_Space'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page",
Test_Create_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content",
Test_Create_Wiki_Content'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Wiki_Page",
Test_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save",
Test_Update_Page'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Create_Wiki_Space (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
W2 : AWA.Wikis.Models.Wiki_Space_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Assert (W.Is_Inserted, "The new wiki space was not created");
W.Set_Name ("Test wiki space update");
W.Set_Is_Public (True);
T.Manager.Save_Wiki_Space (W);
T.Manager.Load_Wiki_Space (Wiki => W2,
Id => W.Get_Id);
Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
"Invalid wiki space name");
end Test_Create_Wiki_Space;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
P.Set_Name ("Private");
P.Set_Title ("The page title");
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
C := AWA.Wikis.Models.Null_Wiki_Content;
P := AWA.Wikis.Models.Null_Wiki_Page;
P.Set_Name ("Public");
P.Set_Title ("The page title (public)");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
T.Assert (P.Get_Is_Public, "The new wiki page is not public");
end Test_Create_Wiki_Page;
-- ------------------------------
-- Test creation of a wiki page content.
-- ------------------------------
procedure Test_Create_Wiki_Content (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Wiki_Id := W.Get_Id;
P.Set_Name ("PrivatePage");
P.Set_Title ("The page title");
P.Set_Is_Public (False);
T.Manager.Create_Wiki_Page (W, P, C);
T.Private_Id := P.Get_Id;
C := AWA.Wikis.Models.Null_Wiki_Content;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
P := AWA.Wikis.Models.Null_Wiki_Page;
C := AWA.Wikis.Models.Null_Wiki_Content;
P.Set_Name ("PublicPage");
P.Set_Title ("The public page title");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Public_Id := P.Get_Id;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph" & ASCII.LF
& "[Link](http://mylink.com)" & ASCII.LF
& "[Image](my-image.png)");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
end Test_Create_Wiki_Content;
-- ------------------------------
-- Test getting the wiki page as well as info, history pages.
-- ------------------------------
procedure Test_Wiki_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PublicPage", "wiki-public-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident,
"wiki-public-info-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage info)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/history/" & Ident & "/" & Pub_Ident,
"wiki-public-history-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage history)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
Request.Remove_Attribute ("wikiView");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PrivatePage", "wiki-private-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PrivatePage)");
Assert_Matches (T, ".*Protected Wiki Page.*", Reply, "Invalid PrivatePage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent", "wiki-list-recent-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent/grid", "wiki-list-grid-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent/grid)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular", "wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular/grid", "wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular/grid)");
end Test_Wiki_Page;
-- ------------------------------
-- Test updating the wiki page through a POST request.
-- ------------------------------
procedure Test_Update_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("page-id", Pub_Ident);
Request.Set_Parameter ("page-wiki-id", Ident);
Request.Set_Parameter ("name", "NewPageName");
Request.Set_Parameter ("page-title", "New Page Title");
Request.Set_Parameter ("text", "== Title ==" & ASCII.LF & "A paragraph" & ASCII.LF
& "[[http://mylink.com|Link]]" & ASCII.LF
& "[[Image:my-image.png|My Picture]]" & ASCII.LF
& "== Last header ==" & ASCII.LF);
Request.Set_Parameter ("comment", "Update through test post simulation");
Request.Set_Parameter ("page-is-public", "TRUE");
Request.Set_Parameter ("wiki-format", "FORMAT_MEDIAWIKI");
Request.Set_Parameter ("qtags[1]", "Test-Tag");
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post", "1");
ASF.Tests.Do_Post (Request, Reply, "/wikis/edit/" & Ident & "/PublicPage",
"update-wiki.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after wiki update");
declare
Result : constant String
:= AWA.Tests.Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/");
begin
Util.Tests.Assert_Equals (T, Ident & "/NewPageName", Result,
"The page name was not updated");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Result, "wiki-public-2.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (NewPageName)");
Assert_Matches (T, ".*Last header.*", Reply,
"Last header is present in the response",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/"
& Pub_Ident, "wiki-info-2.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (info NewPageName)");
Assert_Matches (T, ".*wiki-image-name.*my-image.png.*", Reply,
"The info page must list the image",
Status => ASF.Responses.SC_OK);
end;
end Test_Update_Page;
end AWA.Wikis.Modules.Tests;
|
Implement the Test_Update_Page to check updating a page using a POST request and verify the view and info result page
|
Implement the Test_Update_Page to check updating a page using a POST
request and verify the view and info result page
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e3670464a7795552140df1fe3f53ea4f653713e6
|
regtests/gen-artifacts-yaml-tests.adb
|
regtests/gen-artifacts-yaml-tests.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-yaml-tests -- Tests for YAML model files
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Gen.Configs;
with Gen.Generator;
package body Gen.Artifacts.Yaml.Tests is
use Ada.Strings.Unbounded;
package Caller is new Util.Test_Caller (Test, "Gen.Yaml");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Gen.Yaml.Read_Model",
Test_Read_Yaml'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the YAML files defines in regression tests.
-- ------------------------------
procedure Test_Read_Yaml (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
Path : constant String := Util.Tests.Get_Path ("regtests/files/users.yaml");
Model : Gen.Model.Packages.Model_Definition;
Iter : Gen.Model.Packages.Package_Cursor;
Cnt : Natural := 0;
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_Model (Path, Model, G);
Iter := Model.First;
while Gen.Model.Packages.Has_Element (Iter) loop
Cnt := Cnt + 1;
Gen.Model.Packages.Next (Iter);
end loop;
Util.Tests.Assert_Equals (T, 1, Cnt, "Missing some packages");
end Test_Read_Yaml;
end Gen.Artifacts.Yaml.Tests;
|
-----------------------------------------------------------------------
-- gen-artifacts-yaml-tests -- Tests for YAML model files
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Gen.Generator;
package body Gen.Artifacts.Yaml.Tests is
package Caller is new Util.Test_Caller (Test, "Gen.Yaml");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Gen.Yaml.Read_Model",
Test_Read_Yaml'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the YAML files defines in regression tests.
-- ------------------------------
procedure Test_Read_Yaml (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
Path : constant String := Util.Tests.Get_Path ("regtests/files/users.yaml");
Model : Gen.Model.Packages.Model_Definition;
Iter : Gen.Model.Packages.Package_Cursor;
Cnt : Natural := 0;
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_Model (Path, Model, G);
Iter := Model.First;
while Gen.Model.Packages.Has_Element (Iter) loop
Cnt := Cnt + 1;
Gen.Model.Packages.Next (Iter);
end loop;
Util.Tests.Assert_Equals (T, 1, Cnt, "Missing some packages");
end Test_Read_Yaml;
end Gen.Artifacts.Yaml.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
69a002fd01b995a6e25deeb5ae6063ec40445c32
|
src/asf-components-widgets-inputs.ads
|
src/asf-components-widgets-inputs.ads
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input widget components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Components.Html.Forms;
with ASF.Contexts.Faces;
with ASF.Contexts.Writer;
package ASF.Components.Widgets.Inputs is
use ASF.Contexts.Faces;
use ASF.Contexts.Writer;
-- ------------------------------
-- Input component
-- ------------------------------
-- The AWA input component overrides the ASF input component to build a compact component
-- that displays a label, the input field and the associated error message if necessary.
--
-- The generated HTML looks like:
--
-- <dl class='... awa-error'>
-- <dt>title <i>required</i></dt>
-- <dd><input type='text' ...> <em/>
-- <span class='...'>message</span>
-- </dd>
-- </dl>
type UIInput is new ASF.Components.Html.Forms.UIInput with null record;
type UIInput_Access is access all UIInput'Class;
-- Render the input field title.
procedure Render_Title (UI : in UIInput;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class);
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class);
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class);
end ASF.Components.Widgets.Inputs;
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input widget components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Util.Beans.Basic;
with ASF.Components.Html.Forms;
with ASF.Contexts.Faces;
with ASF.Contexts.Writer;
with ASF.Events.Faces;
package ASF.Components.Widgets.Inputs is
use ASF.Contexts.Faces;
use ASF.Contexts.Writer;
-- ------------------------------
-- Input component
-- ------------------------------
-- The AWA input component overrides the ASF input component to build a compact component
-- that displays a label, the input field and the associated error message if necessary.
--
-- The generated HTML looks like:
--
-- <dl class='... awa-error'>
-- <dt>title <i>required</i></dt>
-- <dd><input type='text' ...> <em/>
-- <span class='...'>message</span>
-- </dd>
-- </dl>
type UIInput is new ASF.Components.Html.Forms.UIInput with null record;
type UIInput_Access is access all UIInput'Class;
-- Render the input field title.
procedure Render_Title (UI : in UIInput;
Name : in String;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class);
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class);
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class);
-- ------------------------------
-- The auto complete component.
-- ------------------------------
--
type UIComplete is new UIInput with private;
type UIComplete_Access is access all UIInput'Class;
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in UIComplete;
Context : in out Faces_Context'Class);
overriding
procedure Process_Decodes (UI : in out UIComplete;
Context : in out Faces_Context'Class);
overriding
procedure Process_Updates (UI : in out UIComplete;
Context : in out Faces_Context'Class);
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
overriding
procedure Broadcast (UI : in out UIComplete;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out Faces_Context'Class);
procedure Render_List (UI : in UIComplete;
Match : in String;
Context : in out Faces_Context'Class);
private
type UIComplete is new UIInput with record
Match_Value : Util.Beans.Objects.Object;
end record;
end ASF.Components.Widgets.Inputs;
|
Define the UIComplete component to provide autocomplete feature of input fields
|
Define the UIComplete component to provide autocomplete feature of input fields
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
32617b043687062f1d28b3638f69528874f2ea3a
|
orka_simd/src/x86/gnat/orka-simd-sse2-integers-convert.ads
|
orka_simd/src/x86/gnat/orka-simd-sse2-integers-convert.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Orka.SIMD.SSE.Singles;
package Orka.SIMD.SSE2.Integers.Convert is
pragma Pure;
use SIMD.SSE.Singles;
function Convert (Elements : m128) return m128i
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_cvtps2dq";
function Convert (Elements : m128i) return m128
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_cvtdq2ps";
end Orka.SIMD.SSE2.Integers.Convert;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2021 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Orka.SIMD.SSE.Singles.Arithmetic;
with Orka.SIMD.SSE2.Integers.Shift;
package Orka.SIMD.SSE2.Integers.Convert is
pragma Pure;
use SIMD.SSE.Singles;
use SIMD.SSE.Singles.Arithmetic;
use SIMD.SSE2.Integers.Shift;
function Convert (Elements : m128) return m128i
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_cvtps2dq";
function Convert (Elements : m128i) return m128
with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_cvtdq2ps";
Smallest_Elements : constant m128 := (others => 2.0**(-24));
function To_Unit_Floats (Elements : m128i) return m128 is
(Convert (Shift_Bits_Right_Zeros (Elements, 8)) * Smallest_Elements)
with Inline;
-- Return floating-point numbers in the 0 .. 1 interval
end Orka.SIMD.SSE2.Integers.Convert;
|
Add function to convert Unsigned_32s to Float_32s in range 0 .. 1
|
simd: Add function to convert Unsigned_32s to Float_32s in range 0 .. 1
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
42c50cd72b75875b0c7f4945e13a7f623ae5afbe
|
src/asf-components-widgets-factory.adb
|
src/asf-components-widgets-factory.adb
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
with ASF.Components.Widgets.Gravatars;
with ASF.Components.Widgets.Likes;
with ASF.Components.Widgets.Panels;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
function Create_Input_Date return UIComponent_Access;
function Create_Complete return UIComponent_Access;
function Create_Gravatar return UIComponent_Access;
function Create_Like return UIComponent_Access;
function Create_Panel return UIComponent_Access;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input_Date return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInputDate;
end Create_Input_Date;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
-- ------------------------------
-- Create a UIGravatar component
-- ------------------------------
function Create_Gravatar return UIComponent_Access is
begin
return new ASF.Components.Widgets.Gravatars.UIGravatar;
end Create_Gravatar;
-- ------------------------------
-- Create a UILike component
-- ------------------------------
function Create_Like return UIComponent_Access is
begin
return new ASF.Components.Widgets.Likes.UILike;
end Create_Like;
-- ------------------------------
-- Create a UIPanel component
-- ------------------------------
function Create_Panel return UIComponent_Access is
begin
return new ASF.Components.Widgets.Panels.UIPanel;
end Create_Panel;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
INPUT_DATE_TAG : aliased constant String := "inputDate";
INPUT_TEXT_TAG : aliased constant String := "inputText";
GRAVATAR_TAG : aliased constant String := "gravatar";
LIKE_TAG : aliased constant String := "like";
PANEL_TAG : aliased constant String := "panel";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => AUTOCOMPLETE_TAG'Access,
Component => Create_Complete'Access,
Tag => Create_Component_Node'Access),
2 => (Name => INPUT_DATE_TAG'Access,
Component => Create_Input_Date'Access,
Tag => Create_Component_Node'Access),
3 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access),
4 => (Name => GRAVATAR_TAG'Access,
Component => Create_Gravatar'Access,
Tag => Create_Component_Node'Access),
5 => (Name => LIKE_TAG'Access,
Component => Create_Like'Access,
Tag => Create_Component_Node'Access),
6 => (Name => PANEL_TAG'Access,
Component => Create_Panel'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
with ASF.Components.Widgets.Gravatars;
with ASF.Components.Widgets.Likes;
with ASF.Components.Widgets.Panels;
with ASF.Components.Widgets.Tabs;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
function Create_Input_Date return UIComponent_Access;
function Create_Complete return UIComponent_Access;
function Create_Gravatar return UIComponent_Access;
function Create_Like return UIComponent_Access;
function Create_Panel return UIComponent_Access;
function Create_TabView return UIComponent_Access;
function Create_Tab return UIComponent_Access;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input_Date return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInputDate;
end Create_Input_Date;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
-- ------------------------------
-- Create a UIGravatar component
-- ------------------------------
function Create_Gravatar return UIComponent_Access is
begin
return new ASF.Components.Widgets.Gravatars.UIGravatar;
end Create_Gravatar;
-- ------------------------------
-- Create a UILike component
-- ------------------------------
function Create_Like return UIComponent_Access is
begin
return new ASF.Components.Widgets.Likes.UILike;
end Create_Like;
-- ------------------------------
-- Create a UIPanel component
-- ------------------------------
function Create_Panel return UIComponent_Access is
begin
return new ASF.Components.Widgets.Panels.UIPanel;
end Create_Panel;
-- ------------------------------
-- Create a UITab component
-- ------------------------------
function Create_Tab return UIComponent_Access is
begin
return new ASF.Components.Widgets.Tabs.UITab;
end Create_Tab;
-- ------------------------------
-- Create a UITabView component
-- ------------------------------
function Create_TabView return UIComponent_Access is
begin
return new ASF.Components.Widgets.Tabs.UITabView;
end Create_TabView;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
INPUT_DATE_TAG : aliased constant String := "inputDate";
INPUT_TEXT_TAG : aliased constant String := "inputText";
GRAVATAR_TAG : aliased constant String := "gravatar";
LIKE_TAG : aliased constant String := "like";
PANEL_TAG : aliased constant String := "panel";
TAB_TAG : aliased constant String := "tab";
TAB_VIEW_TAG : aliased constant String := "tabView";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => AUTOCOMPLETE_TAG'Access,
Component => Create_Complete'Access,
Tag => Create_Component_Node'Access),
2 => (Name => INPUT_DATE_TAG'Access,
Component => Create_Input_Date'Access,
Tag => Create_Component_Node'Access),
3 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access),
4 => (Name => GRAVATAR_TAG'Access,
Component => Create_Gravatar'Access,
Tag => Create_Component_Node'Access),
5 => (Name => LIKE_TAG'Access,
Component => Create_Like'Access,
Tag => Create_Component_Node'Access),
6 => (Name => PANEL_TAG'Access,
Component => Create_Panel'Access,
Tag => Create_Component_Node'Access),
7 => (Name => TAB_TAG'Access,
Component => Create_Tab'Access,
Tag => Create_Component_Node'Access),
8 => (Name => TAB_VIEW_TAG'Access,
Component => Create_TabView'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
Add the new <w:tab> and <w:tabView> components in the factory
|
Add the new <w:tab> and <w:tabView> components in the factory
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
6215c8f966979e56d3ac5c3806ad314a42f1a0be
|
ARM/STMicro/STM32/drivers/ltdc/stm32-ltdc-init.adb
|
ARM/STMicro/STM32/drivers/ltdc/stm32-ltdc-init.adb
|
with STM32_SVD.Interrupts;
separate (STM32.LTDC)
package body Init is
pragma Warnings (Off, "* is not referenced");
type LCD_Polarity is
(Polarity_Active_Low,
Polarity_Active_High) with Size => 1;
type LCD_PC_Polarity is
(Input_Pixel_Clock,
Inverted_Input_Pixel_Clock) with Size => 1;
pragma Warnings (On, "* is not referenced");
function To_Bit is new Ada.Unchecked_Conversion (LCD_Polarity, Bit);
function To_Bit is new Ada.Unchecked_Conversion (LCD_PC_Polarity, Bit);
-- Extracted from STM32F429x.LTDC
type Layer_Type is record
LCR : L1CR_Register; -- Layerx Control Register
LWHPCR : L1WHPCR_Register; -- Layerx Window Horizontal Position Configuration Register
LWVPCR : L1WVPCR_Register; -- Layerx Window Vertical Position Configuration Register
LCKCR : L1CKCR_Register; -- Layerx Color Keying Configuration Register
LPFCR : L1PFCR_Register; -- Layerx Pixel Format Configuration Register
LCACR : L1CACR_Register; -- Layerx Constant Alpha Configuration Register
LDCCR : L1DCCR_Register; -- Layerx Default Color Configuration Register
LBFCR : L1BFCR_Register; -- Layerx Blending Factors Configuration Register
Reserved_0 : Word;
Reserved_1 : Word;
LCFBAR : Word; -- Layerx Color Frame Buffer Address Register
LCFBLR : L1CFBLR_Register; -- Layerx Color Frame Buffer Length Register
LCFBLNR : L1CFBLNR_Register; -- Layerx ColorFrame Buffer Line Number Register
Reserved_2 : Word;
Reserved_3 : Word;
Reserved_4 : Word;
LCLUTWR : L1CLUTWR_Register; -- Layerx CLUT Write Register
end record with Volatile;
for Layer_Type use record
LCR at 0 range 0 .. 31;
LWHPCR at 4 range 0 .. 31;
LWVPCR at 8 range 0 .. 31;
LCKCR at 12 range 0 .. 31;
LPFCR at 16 range 0 .. 31;
LCACR at 20 range 0 .. 31;
LDCCR at 24 range 0 .. 31;
LBFCR at 28 range 0 .. 31;
Reserved_0 at 32 range 0 .. 31;
Reserved_1 at 36 range 0 .. 31;
LCFBAR at 40 range 0 .. 31;
LCFBLR at 44 range 0 .. 31;
LCFBLNR at 48 range 0 .. 31;
Reserved_2 at 52 range 0 .. 31;
Reserved_3 at 56 range 0 .. 31;
Reserved_4 at 60 range 0 .. 31;
LCLUTWR at 64 range 0 .. 31;
end record;
type Layer_Access is access all Layer_Type;
G_Layer1_Reg : aliased Layer_Type
with Import, Address => LTDC_Periph.L1CR'Address;
G_Layer2_Reg : aliased Layer_Type
with Import, Address => LTDC_Periph.L2CR'Address;
type Pending_Buffers is array (LCD_Layer) of Word;
protected Sync is
-- Sets the next buffer to setup
procedure Set_Pending (Layer : LCD_Layer;
Buffer : Word);
-- Apply pending buffers without waiting for the interrupt
procedure Apply_Immediate;
-- Wait for an interrupt.
entry Wait;
procedure Interrupt;
pragma Attach_Handler
(Interrupt, STM32_SVD.Interrupts.LCD_TFT_Interrupt);
private
Pending : Boolean := False;
Buffers : Pending_Buffers := (others => 0);
end Sync;
protected body Sync is
-----------------
-- Set_Pending --
-----------------
procedure Set_Pending
(Layer : LCD_Layer;
Buffer : Word)
is
begin
Pending := True;
LTDC_Periph.IER.LIE := 1;
LTDC_Periph.LIPCR.LIPOS := 0;
Buffers (Layer) := Buffer;
end Set_Pending;
----------
-- Wait --
----------
entry Wait when not Pending is
begin
null;
end Wait;
---------------------
-- Apply_Immediate --
---------------------
procedure Apply_Immediate is
begin
LTDC_Periph.IER.LIE := 0;
if Buffers (Layer1) /= 0 then
LTDC_Periph.L1CFBAR := Buffers (Layer1);
Buffers (Layer1) := 0;
end if;
if Buffers (Layer2) /= 0 then
LTDC_Periph.L2CFBAR := Buffers (Layer2);
Buffers (Layer2) := 0;
end if;
LTDC_Periph.SRCR.IMR := 1;
loop
exit when LTDC_Periph.SRCR.IMR = 0;
end loop;
Pending := False;
LTDC_Periph.IER.LIE := 1;
end Apply_Immediate;
---------------
-- Interrupt --
---------------
procedure Interrupt
is
begin
LTDC_Periph.IER.LIE := 0;
LTDC_Periph.ICR.CLIF := 1;
Apply_Immediate;
end Interrupt;
end Sync;
---------------
-- Get_Layer --
---------------
function Get_Layer (Layer : LCD_Layer) return Layer_Access is
begin
if Layer = Layer1 then
return G_Layer1_Reg'Access;
else
return G_Layer2_Reg'Access;
end if;
end Get_Layer;
--------------------
-- Set_Layer_CFBA --
--------------------
procedure Set_Layer_CFBA (Layer : LCD_Layer;
FBA : Frame_Buffer_Access)
is
-- L : constant Layer_Access := Get_Layer (Layer);
function To_Word is new Ada.Unchecked_Conversion
(Frame_Buffer_Access, Word);
begin
Sync.Set_Pending (Layer, To_Word (FBA));
-- L.LCFBAR := To_Word (FBA);
end Set_Layer_CFBA;
--------------------
-- Get_Layer_CFBA --
--------------------
function Get_Layer_CFBA
(Layer : LCD_Layer) return Frame_Buffer_Access
is
L : constant Layer_Access := Get_Layer (Layer);
function To_FBA is new Ada.Unchecked_Conversion
(Word, Frame_Buffer_Access);
begin
return To_FBA (L.LCFBAR);
end Get_Layer_CFBA;
---------------------
-- Set_Layer_State --
---------------------
procedure Set_Layer_State
(Layer : LCD_Layer;
State : Boolean)
is
L : constant Layer_Access := Get_Layer (Layer);
Val : constant Bit := (if State then 1 else 0);
begin
if State and then Frame_Buffer_Array (Layer) = Null_Address then
Frame_Buffer_Array (Layer) := STM32.SDRAM.Reserve
(Word (LCD_Width * LCD_Height * Pixel_Size (Current_Pixel_Fmt)));
Set_Layer_CFBA (Layer, Frame_Buffer_Array (Layer));
end if;
if L.LCR.LEN /= Val then
L.LCR.LEN := Val;
Reload_Config (Immediate => True);
else
L.LCR.LEN := (if state then 1 else 0);
end if;
end Set_Layer_State;
-------------------
-- Reload_Config --
-------------------
procedure Reload_Config (Immediate : Boolean) is
begin
if Immediate then
Sync.Apply_Immediate;
else
Sync.Wait;
end if;
end Reload_Config;
---------------
-- LTDC_Init --
---------------
procedure LTDC_Init
is
DivR_Val : PLLSAI_DivR;
begin
RCC_Periph.APB2ENR.LTDCEN := 1;
LTDC_Periph.GCR.VSPOL := To_Bit (Polarity_Active_Low);
LTDC_Periph.GCR.HSPOL := To_Bit (Polarity_Active_Low);
LTDC_Periph.GCR.DEPOL := To_Bit (Polarity_Active_Low);
LTDC_Periph.GCR.PCPOL := To_Bit (Input_Pixel_Clock);
if DivR = 2 then
DivR_Val := PLLSAI_DIV2;
elsif DivR = 4 then
DivR_Val := PLLSAI_DIV4;
elsif DivR = 8 then
DivR_Val := PLLSAI_DIV8;
elsif DivR = 16 then
DivR_Val := PLLSAI_DIV16;
else
raise Constraint_Error with "Invalid DivR value: 2, 4, 8, 16 allowed";
end if;
Disable_PLLSAI;
Set_PLLSAI_Factors
(LCD => PLLSAI_R,
VCO => PLLSAI_N,
DivR => DivR_Val);
Enable_PLLSAI;
-- Synchronization size
LTDC_Periph.SSCR :=
(HSW => SSCR_HSW_Field (LCD_HSync - 1),
VSH => SSCR_VSH_Field (LCD_VSync - 1),
others => <>);
-- Accumulated Back Porch
LTDC_Periph.BPCR :=
(AHBP => BPCR_AHBP_Field (LCD_HSync + LCD_HBP - 1),
AVBP => BPCR_AVBP_Field (LCD_VSync + LCD_VBP - 1),
others => <>);
-- Accumulated Active Width/Height
LTDC_Periph.AWCR :=
(AAW => AWCR_AAW_Field (LCD_HSync + LCD_HBP + LCD_Width - 1),
AAH => AWCR_AAH_FIeld (LCD_VSync + LCD_VBP + LCD_Height - 1),
others => <>);
-- VTotal Width/Height
LTDC_Periph.TWCR :=
(TOTALW =>
TWCR_TOTALW_Field (LCD_HSync + LCD_HBP + LCD_Width + LCD_HFP - 1),
TOTALH =>
TWCR_TOTALH_Field (LCD_VSync + LCD_VBP + LCD_Height + LCD_VFP - 1),
others => <>);
-- Background color to black
LTDC_Periph.BCCR.BC := 0;
Reload_Config (True);
LTDC_Periph.GCR.LTDCEN := 1;
end LTDC_Init;
-----------------
-- Layers_Init --
-----------------
procedure Layer_Init
(Layer : LCD_Layer;
Config : Pixel_Format;
BF1, BF2 : UInt3)
is
L : constant Layer_Access := Get_Layer (Layer);
CFBL : L1CFBLR_Register := L.LCFBLR;
begin
-- Horizontal start and stop = sync + Back Porch
L.LWHPCR :=
(WHSTPOS => UInt12 (LCD_HSync + LCD_HBP),
WHSPPOS => UInt12 (LCD_HSync + LCD_HBP + LCD_Width - 1),
others => <>);
-- Vertical start and stop
L.LWVPCR :=
(WVSTPOS => UInt11 (LCD_VSync + LCD_VBP),
WVSPPOS => UInt11 (LCD_VSync + LCD_VBP + LCD_Height - 1),
others => <>);
L.LPFCR.PF := Pixel_Format'Enum_Rep (Config);
L.LCACR.CONSTA := 255;
L.LDCCR := (others => 0);
L.LBFCR.BF1 := BF1;
L.LBFCR.BF2 := BF2;
CFBL.CFBLL := UInt13 (LCD_Width * Pixel_Size (Config)) + 3;
CFBL.CFBP := UInt13 (LCD_Width * Pixel_Size (Config));
L.LCFBLR := CFBL;
L.LCFBLNR.CFBLNBR := UInt11 (LCD_Height);
Set_Layer_CFBA (Layer, Frame_Buffer_Array (Layer));
Reload_Config (True);
end Layer_Init;
end Init;
|
with STM32_SVD.Interrupts;
separate (STM32.LTDC)
package body Init is
pragma Warnings (Off, "* is not referenced");
type LCD_Polarity is
(Polarity_Active_Low,
Polarity_Active_High) with Size => 1;
type LCD_PC_Polarity is
(Input_Pixel_Clock,
Inverted_Input_Pixel_Clock) with Size => 1;
pragma Warnings (On, "* is not referenced");
function To_Bit is new Ada.Unchecked_Conversion (LCD_Polarity, Bit);
function To_Bit is new Ada.Unchecked_Conversion (LCD_PC_Polarity, Bit);
-- Extracted from STM32F429x.LTDC
type Layer_Type is record
LCR : L1CR_Register; -- Layerx Control Register
LWHPCR : L1WHPCR_Register; -- Layerx Window Horizontal Position Configuration Register
LWVPCR : L1WVPCR_Register; -- Layerx Window Vertical Position Configuration Register
LCKCR : L1CKCR_Register; -- Layerx Color Keying Configuration Register
LPFCR : L1PFCR_Register; -- Layerx Pixel Format Configuration Register
LCACR : L1CACR_Register; -- Layerx Constant Alpha Configuration Register
LDCCR : L1DCCR_Register; -- Layerx Default Color Configuration Register
LBFCR : L1BFCR_Register; -- Layerx Blending Factors Configuration Register
Reserved_0 : Word;
Reserved_1 : Word;
LCFBAR : Word; -- Layerx Color Frame Buffer Address Register
LCFBLR : L1CFBLR_Register; -- Layerx Color Frame Buffer Length Register
LCFBLNR : L1CFBLNR_Register; -- Layerx ColorFrame Buffer Line Number Register
Reserved_2 : Word;
Reserved_3 : Word;
Reserved_4 : Word;
LCLUTWR : L1CLUTWR_Register; -- Layerx CLUT Write Register
end record with Volatile;
for Layer_Type use record
LCR at 0 range 0 .. 31;
LWHPCR at 4 range 0 .. 31;
LWVPCR at 8 range 0 .. 31;
LCKCR at 12 range 0 .. 31;
LPFCR at 16 range 0 .. 31;
LCACR at 20 range 0 .. 31;
LDCCR at 24 range 0 .. 31;
LBFCR at 28 range 0 .. 31;
Reserved_0 at 32 range 0 .. 31;
Reserved_1 at 36 range 0 .. 31;
LCFBAR at 40 range 0 .. 31;
LCFBLR at 44 range 0 .. 31;
LCFBLNR at 48 range 0 .. 31;
Reserved_2 at 52 range 0 .. 31;
Reserved_3 at 56 range 0 .. 31;
Reserved_4 at 60 range 0 .. 31;
LCLUTWR at 64 range 0 .. 31;
end record;
type Layer_Access is access all Layer_Type;
G_Layer1_Reg : aliased Layer_Type
with Import, Address => LTDC_Periph.L1CR'Address;
G_Layer2_Reg : aliased Layer_Type
with Import, Address => LTDC_Periph.L2CR'Address;
type Pending_Buffers is array (LCD_Layer) of Word;
protected Sync is
-- Sets the next buffer to setup
procedure Set_Pending (Layer : LCD_Layer;
Buffer : Word);
-- Apply pending buffers without waiting for the interrupt
procedure Apply_Immediate;
-- Wait for an interrupt.
entry Wait;
procedure Interrupt;
pragma Attach_Handler
(Interrupt, STM32_SVD.Interrupts.LCD_TFT_Interrupt);
private
Not_Pending : Boolean := True;
Buffers : Pending_Buffers := (others => 0);
end Sync;
protected body Sync is
-----------------
-- Set_Pending --
-----------------
procedure Set_Pending
(Layer : LCD_Layer;
Buffer : Word)
is
begin
Not_Pending := False;
LTDC_Periph.IER.LIE := 1;
LTDC_Periph.LIPCR.LIPOS := 0;
Buffers (Layer) := Buffer;
end Set_Pending;
----------
-- Wait --
----------
entry Wait when Not_Pending is
begin
null;
end Wait;
---------------------
-- Apply_Immediate --
---------------------
procedure Apply_Immediate is
begin
LTDC_Periph.IER.LIE := 0;
if Buffers (Layer1) /= 0 then
LTDC_Periph.L1CFBAR := Buffers (Layer1);
Buffers (Layer1) := 0;
end if;
if Buffers (Layer2) /= 0 then
LTDC_Periph.L2CFBAR := Buffers (Layer2);
Buffers (Layer2) := 0;
end if;
LTDC_Periph.SRCR.IMR := 1;
loop
exit when LTDC_Periph.SRCR.IMR = 0;
end loop;
Not_Pending := True;
LTDC_Periph.IER.LIE := 1;
end Apply_Immediate;
---------------
-- Interrupt --
---------------
procedure Interrupt
is
begin
LTDC_Periph.IER.LIE := 0;
LTDC_Periph.ICR.CLIF := 1;
Apply_Immediate;
end Interrupt;
end Sync;
---------------
-- Get_Layer --
---------------
function Get_Layer (Layer : LCD_Layer) return Layer_Access is
begin
if Layer = Layer1 then
return G_Layer1_Reg'Access;
else
return G_Layer2_Reg'Access;
end if;
end Get_Layer;
--------------------
-- Set_Layer_CFBA --
--------------------
procedure Set_Layer_CFBA (Layer : LCD_Layer;
FBA : Frame_Buffer_Access)
is
-- L : constant Layer_Access := Get_Layer (Layer);
function To_Word is new Ada.Unchecked_Conversion
(Frame_Buffer_Access, Word);
begin
Sync.Set_Pending (Layer, To_Word (FBA));
-- L.LCFBAR := To_Word (FBA);
end Set_Layer_CFBA;
--------------------
-- Get_Layer_CFBA --
--------------------
function Get_Layer_CFBA
(Layer : LCD_Layer) return Frame_Buffer_Access
is
L : constant Layer_Access := Get_Layer (Layer);
function To_FBA is new Ada.Unchecked_Conversion
(Word, Frame_Buffer_Access);
begin
return To_FBA (L.LCFBAR);
end Get_Layer_CFBA;
---------------------
-- Set_Layer_State --
---------------------
procedure Set_Layer_State
(Layer : LCD_Layer;
State : Boolean)
is
L : constant Layer_Access := Get_Layer (Layer);
Val : constant Bit := (if State then 1 else 0);
begin
if State and then Frame_Buffer_Array (Layer) = Null_Address then
Frame_Buffer_Array (Layer) := STM32.SDRAM.Reserve
(Word (LCD_Width * LCD_Height * Pixel_Size (Current_Pixel_Fmt)));
Set_Layer_CFBA (Layer, Frame_Buffer_Array (Layer));
end if;
if L.LCR.LEN /= Val then
L.LCR.LEN := Val;
Reload_Config (Immediate => True);
else
L.LCR.LEN := (if state then 1 else 0);
end if;
end Set_Layer_State;
-------------------
-- Reload_Config --
-------------------
procedure Reload_Config (Immediate : Boolean) is
begin
if Immediate then
Sync.Apply_Immediate;
else
Sync.Wait;
end if;
end Reload_Config;
---------------
-- LTDC_Init --
---------------
procedure LTDC_Init
is
DivR_Val : PLLSAI_DivR;
begin
RCC_Periph.APB2ENR.LTDCEN := 1;
LTDC_Periph.GCR.VSPOL := To_Bit (Polarity_Active_Low);
LTDC_Periph.GCR.HSPOL := To_Bit (Polarity_Active_Low);
LTDC_Periph.GCR.DEPOL := To_Bit (Polarity_Active_Low);
LTDC_Periph.GCR.PCPOL := To_Bit (Input_Pixel_Clock);
if DivR = 2 then
DivR_Val := PLLSAI_DIV2;
elsif DivR = 4 then
DivR_Val := PLLSAI_DIV4;
elsif DivR = 8 then
DivR_Val := PLLSAI_DIV8;
elsif DivR = 16 then
DivR_Val := PLLSAI_DIV16;
else
raise Constraint_Error with "Invalid DivR value: 2, 4, 8, 16 allowed";
end if;
Disable_PLLSAI;
Set_PLLSAI_Factors
(LCD => PLLSAI_R,
VCO => PLLSAI_N,
DivR => DivR_Val);
Enable_PLLSAI;
-- Synchronization size
LTDC_Periph.SSCR :=
(HSW => SSCR_HSW_Field (LCD_HSync - 1),
VSH => SSCR_VSH_Field (LCD_VSync - 1),
others => <>);
-- Accumulated Back Porch
LTDC_Periph.BPCR :=
(AHBP => BPCR_AHBP_Field (LCD_HSync + LCD_HBP - 1),
AVBP => BPCR_AVBP_Field (LCD_VSync + LCD_VBP - 1),
others => <>);
-- Accumulated Active Width/Height
LTDC_Periph.AWCR :=
(AAW => AWCR_AAW_Field (LCD_HSync + LCD_HBP + LCD_Width - 1),
AAH => AWCR_AAH_FIeld (LCD_VSync + LCD_VBP + LCD_Height - 1),
others => <>);
-- VTotal Width/Height
LTDC_Periph.TWCR :=
(TOTALW =>
TWCR_TOTALW_Field (LCD_HSync + LCD_HBP + LCD_Width + LCD_HFP - 1),
TOTALH =>
TWCR_TOTALH_Field (LCD_VSync + LCD_VBP + LCD_Height + LCD_VFP - 1),
others => <>);
-- Background color to black
LTDC_Periph.BCCR.BC := 0;
Reload_Config (True);
LTDC_Periph.GCR.LTDCEN := 1;
end LTDC_Init;
-----------------
-- Layers_Init --
-----------------
procedure Layer_Init
(Layer : LCD_Layer;
Config : Pixel_Format;
BF1, BF2 : UInt3)
is
L : constant Layer_Access := Get_Layer (Layer);
CFBL : L1CFBLR_Register := L.LCFBLR;
begin
-- Horizontal start and stop = sync + Back Porch
L.LWHPCR :=
(WHSTPOS => UInt12 (LCD_HSync + LCD_HBP),
WHSPPOS => UInt12 (LCD_HSync + LCD_HBP + LCD_Width - 1),
others => <>);
-- Vertical start and stop
L.LWVPCR :=
(WVSTPOS => UInt11 (LCD_VSync + LCD_VBP),
WVSPPOS => UInt11 (LCD_VSync + LCD_VBP + LCD_Height - 1),
others => <>);
L.LPFCR.PF := Pixel_Format'Enum_Rep (Config);
L.LCACR.CONSTA := 255;
L.LDCCR := (others => 0);
L.LBFCR.BF1 := BF1;
L.LBFCR.BF2 := BF2;
CFBL.CFBLL := UInt13 (LCD_Width * Pixel_Size (Config)) + 3;
CFBL.CFBP := UInt13 (LCD_Width * Pixel_Size (Config));
L.LCFBLR := CFBL;
L.LCFBLNR.CFBLNBR := UInt11 (LCD_Height);
Set_Layer_CFBA (Layer, Frame_Buffer_Array (Layer));
Reload_Config (True);
end Layer_Init;
end Init;
|
Fix simple barier in LTDC driver (ravenscar-sfp limitation).
|
Fix simple barier in LTDC driver (ravenscar-sfp limitation).
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
3198edc3a39a4b818e00615f808e0400c161606f
|
src/sqlite/ado-drivers-connections-sqlite.adb
|
src/sqlite/ado-drivers-connections-sqlite.adb
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with Util.Processes.Tools;
with ADO.Sessions;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Drivers.Connections.Sqlite is
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Rollback;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
Result : int;
begin
Log.Info ("Close connection {0}", Database.Name);
if Database.Server /= null then
Result := Sqlite3_H.sqlite3_close_v2 (Database.Server);
if Result /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot close database {0}: {1}", To_String (Database.Name), Msg);
end;
end if;
Database.Server := null;
end if;
end Close;
-- ------------------------------
-- Releases the sqlite connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
begin
Log.Debug ("Release database connection");
if Database.Server /= null then
Database.Close;
end if;
end Finalize;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
-- ------------------------------
-- Create the database and initialize it with the schema SQL file.
-- ------------------------------
procedure Create_Database (Database : in Database_Connection;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is
pragma Unreferenced (Database);
Status : Integer;
Database_Path : constant String := Config.Get_Database;
Command : constant String :=
"sqlite3 --batch --init " & Schema_Path & " " & Database_Path;
begin
Log.Info ("Creating SQLite database {0}", Database_Path);
Messages.Clear;
Util.Processes.Tools.Execute (Command, Messages, Status);
if Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Status = 255 then
Messages.Append ("Command not found: " & Command);
Log.Error ("Command not found: {0}", Command);
else
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Status));
end if;
end Create_Database;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
pragma Unreferenced (D);
use Strings;
Name : constant String := Config.Get_Database;
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased access Sqlite3;
Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
Log.Info ("Opening database {0}", Name);
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot open SQLite database: {0}", Msg);
raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg;
end;
end if;
declare
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name : in String;
Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := Util.Properties.To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name : in String;
Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item);
begin
if Util.Strings.Index (Name, '.') = 0 then
Log.Info ("Configure database with {0}", SQL);
ADO.Statements.Sqlite.Execute (Database.Server, SQL);
end if;
exception
when SQL_Error =>
null;
end Configure;
begin
Database.Server := Handle;
Database.Name := To_Unbounded_String (Config.Get_Database);
Result := Ref.Create (Database.all'Access);
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Iterate (Process => Configure'Access);
end;
end Create_Connection;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
end ADO.Drivers.Connections.Sqlite;
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with Util.Processes.Tools;
with ADO.Sessions;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Drivers.Connections.Sqlite is
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Rollback;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
Result : int;
begin
Log.Info ("Close connection {0}", Database.Name);
if Database.Server /= null then
Result := Sqlite3_H.sqlite3_close_v2 (Database.Server);
if Result /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot close database {0}: {1}", To_String (Database.Name), Msg);
end;
end if;
Database.Server := null;
end if;
end Close;
-- ------------------------------
-- Releases the sqlite connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
begin
Log.Debug ("Release database connection");
if Database.Server /= null then
Database.Close;
end if;
end Finalize;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
pragma Unreferenced (D);
use Strings;
Name : constant String := Config.Get_Database;
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased access Sqlite3;
Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
Log.Info ("Opening database {0}", Name);
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot open SQLite database: {0}", Msg);
raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg;
end;
end if;
declare
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name : in String;
Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := Util.Properties.To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name : in String;
Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item);
begin
if Util.Strings.Index (Name, '.') = 0 then
Log.Info ("Configure database with {0}", SQL);
ADO.Statements.Sqlite.Execute (Database.Server, SQL);
end if;
exception
when SQL_Error =>
null;
end Configure;
begin
Database.Server := Handle;
Database.Name := To_Unbounded_String (Config.Get_Database);
Result := Ref.Create (Database.all'Access);
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Iterate (Process => Configure'Access);
end;
end Create_Connection;
-- ------------------------------
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
-- ------------------------------
overriding
procedure Create_Database (D : in out Sqlite_Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is
pragma Unreferenced (D, Admin);
Status : Integer;
Database_Path : constant String := Config.Get_Database;
Command : constant String :=
"sqlite3 --batch --init " & Schema_Path & " " & Database_Path;
begin
Log.Info ("Creating SQLite database {0}", Database_Path);
Util.Processes.Tools.Execute (Command, Messages, Status);
if Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Status = 255 then
Messages.Append ("Command not found: " & Command);
Log.Error ("Command not found: {0}", Command);
else
Messages.Append ("Command " & Command & " failed with exit code "
& Util.Strings.Image (Status));
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Status));
end if;
end Create_Database;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
end ADO.Drivers.Connections.Sqlite;
|
Move the Create_Database operation on the Driver instead of the database connection
|
Move the Create_Database operation on the Driver instead of the database connection
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
86196e99d5d4f6fe2acb56ca2bf4e3540085e8ef
|
src/sqlite/ado-drivers-connections-sqlite.adb
|
src/sqlite/ado-drivers-connections-sqlite.adb
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with Util.Processes.Tools;
with ADO.Sessions;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Drivers.Connections.Sqlite is
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Rollback;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
Log.Info ("Close connection {0}", Database.Name);
end Close;
-- ------------------------------
-- Releases the sqlite connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
Result : int;
begin
Log.Debug ("Release database connection");
if Database.Server /= null then
Result := Sqlite3_H.sqlite3_close_v2 (Database.Server);
if Result /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot close database {0}: {1}", To_String (Database.Name), Msg);
end;
end if;
Database.Server := null;
end if;
end Finalize;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
protected body Sqlite_Connections is
procedure Open (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
use Strings;
URI : constant String := Config.Get_URI;
Pos : Database_List.Cursor := Database_List.First (List);
C : Database_Connection_Access;
begin
-- Look first in the database list.
while Database_List.Has_Element (Pos) loop
C := Database_Connection'Class (Database_List.Element (Pos).Value.all)'Access;
if C.URI = URI then
Result := Ref.Ref'Class (Database_List.Element (Pos));
return;
end if;
Database_List.Next (Pos);
end loop;
-- Now we can open a new database connection.
declare
Name : constant String := Config.Get_Database;
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased access Sqlite3;
Flags : constant int
:= Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot open SQLite database: {0}", Msg);
raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg;
end;
end if;
declare
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name : in String;
Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := Util.Properties.To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name : in String;
Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item);
begin
if Util.Strings.Index (Name, '.') = 0 then
Log.Info ("Configure database with {0}", SQL);
ADO.Statements.Sqlite.Execute (Database.Server, SQL);
end if;
exception
when SQL_Error =>
null;
end Configure;
begin
Database.Server := Handle;
Database.Name := To_Unbounded_String (Config.Get_Database);
Database.URI := To_Unbounded_String (URI);
Result := Ref.Create (Database.all'Access);
Database_List.Prepend (Container => List, New_Item => Ref.Ref (Result));
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Iterate (Process => Configure'Access);
end;
end;
end Open;
end Sqlite_Connections;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
begin
D.Map.Open (Config, Result);
end Create_Connection;
-- ------------------------------
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
-- ------------------------------
overriding
procedure Create_Database (D : in out Sqlite_Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is
pragma Unreferenced (D, Admin);
Status : Integer;
Database_Path : constant String := Config.Get_Database;
Command : constant String :=
"sqlite3 --batch --init " & Schema_Path & " " & Database_Path;
begin
Log.Info ("Creating SQLite database {0}", Database_Path);
Util.Processes.Tools.Execute (Command, Messages, Status);
if Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Status = 255 then
Messages.Append ("Command not found: " & Command);
Log.Error ("Command not found: {0}", Command);
else
Messages.Append ("Command " & Command & " failed with exit code "
& Util.Strings.Image (Status));
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Status));
end if;
end Create_Database;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the SQLite driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Sqlite_Driver) is
pragma Unreferenced (D);
begin
Log.Debug ("Deleting the sqlite driver");
end Finalize;
end ADO.Drivers.Connections.Sqlite;
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with Util.Processes.Tools;
with ADO.Sessions;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Drivers.Connections.Sqlite is
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
if Database.Server = null then
raise ADO.Sessions.Session_Error with "Database connection is closed";
end if;
end Rollback;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
Log.Info ("Close connection {0}", Database.Name);
Database.Server := null;
end Close;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
protected body Sqlite_Connections is
procedure Open (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
use Strings;
URI : constant String := Config.Get_URI;
Database : Database_Connection_Access;
Pos : Database_List.Cursor := Database_List.First (List);
DB : SQLite_Database;
begin
-- Look first in the database list.
while Database_List.Has_Element (Pos) loop
DB := Database_List.Element (Pos);
if DB.URI = URI then
Database := new Database_Connection;
Database.URI := DB.URI;
Database.Name := DB.Name;
Database.Server := DB.Server;
Result := Ref.Create (Database.all'Access);
return;
end if;
Database_List.Next (Pos);
end loop;
-- Now we can open a new database connection.
declare
Name : constant String := Config.Get_Database;
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased access Sqlite3;
Flags : constant int
:= Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot open SQLite database: {0}", Msg);
raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg;
end;
end if;
Database := new Database_Connection;
declare
procedure Configure (Name : in String;
Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := Util.Properties.To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name : in String;
Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item);
begin
if Util.Strings.Index (Name, '.') = 0 then
Log.Info ("Configure database with {0}", SQL);
ADO.Statements.Sqlite.Execute (Database.Server, SQL);
end if;
exception
when SQL_Error =>
null;
end Configure;
begin
Database.Server := Handle;
Database.Name := To_Unbounded_String (Config.Get_Database);
Database.URI := To_Unbounded_String (URI);
Result := Ref.Create (Database.all'Access);
DB.Server := Handle;
DB.Name := Database.Name;
DB.URI := Database.URI;
Database_List.Prepend (Container => List, New_Item => DB);
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Iterate (Process => Configure'Access);
end;
end;
end Open;
procedure Clear is
DB : SQLite_Database;
Result : int;
begin
while not Database_List.Is_Empty (List) loop
DB := Database_List.First_Element (List);
Database_List.Delete_First (List);
if DB.Server /= null then
Result := Sqlite3_H.sqlite3_close_v2 (DB.Server);
if Result /= Sqlite3_H.SQLITE_OK then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Cannot close database {0}: {1}", To_String (DB.Name), Msg);
end;
end if;
end if;
end loop;
end Clear;
end Sqlite_Connections;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
begin
D.Map.Open (Config, Result);
end Create_Connection;
-- ------------------------------
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
-- ------------------------------
overriding
procedure Create_Database (D : in out Sqlite_Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is
pragma Unreferenced (D, Admin);
Status : Integer;
Database_Path : constant String := Config.Get_Database;
Command : constant String :=
"sqlite3 --batch --init " & Schema_Path & " " & Database_Path;
begin
Log.Info ("Creating SQLite database {0}", Database_Path);
Util.Processes.Tools.Execute (Command, Messages, Status);
if Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Status = 255 then
Messages.Append ("Command not found: " & Command);
Log.Error ("Command not found: {0}", Command);
else
Messages.Append ("Command " & Command & " failed with exit code "
& Util.Strings.Image (Status));
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Status));
end if;
end Create_Database;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the SQLite driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Sqlite_Driver) is
begin
Log.Debug ("Deleting the sqlite driver");
D.Map.Clear;
end Finalize;
end ADO.Drivers.Connections.Sqlite;
|
Change the database management better follow previous version behaviors - Remove the Finalize on the Database_Connection - Move the database close in protected Clear operation - Update protected Open operation to use the SQLite_Database record
|
Change the database management better follow previous version behaviors
- Remove the Finalize on the Database_Connection
- Move the database close in protected Clear operation
- Update protected Open operation to use the SQLite_Database record
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
f410270b61a469e11862e1ea40e0ae47a99df45f
|
src/natools-web-error_pages.adb
|
src/natools-web-error_pages.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.Caches;
with Natools.S_Expressions.Lockable;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.Static_Maps.Web.Error_Pages;
package body Natools.Web.Error_Pages is
procedure Append
(Exchange : in out Sites.Exchange;
Context : in Error_Context;
Data : in S_Expressions.Atom);
procedure Default_Page
(Exchange : in out Sites.Exchange;
Context : in Error_Context);
procedure Execute
(Exchange : in out Sites.Exchange;
Context : in Error_Context;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
-------------------------
-- Error Page Renderer --
-------------------------
procedure Append
(Exchange : in out Sites.Exchange;
Context : in Error_Context;
Data : in S_Expressions.Atom)
is
pragma Unreferenced (Context);
begin
Exchange.Append (Data);
end Append;
procedure Default_Page
(Exchange : in out Sites.Exchange;
Context : in Error_Context)
is
begin
Exchange.Append (S_Expressions.To_Atom ("<html><head><title>Error "));
Exchange.Append (Context.Code);
Exchange.Append
(S_Expressions.To_Atom ("</title></head><body><h1>Error "));
Exchange.Append (Context.Code);
Exchange.Append (S_Expressions.To_Atom ("</h1><p>"));
Exchange.Append
(S_Expressions.To_Atom
(Natools.Static_Maps.Web.Error_Pages.To_Message
(S_Expressions.To_String (Context.Code))));
Exchange.Append (S_Expressions.To_Atom ("</p></body></html>"));
end Default_Page;
procedure Execute
(Exchange : in out Sites.Exchange;
Context : in Error_Context;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Arguments);
use Natools.Static_Maps.Web.Error_Pages;
begin
case To_Command (S_Expressions.To_String (Name)) is
when Unknown_Command =>
null;
when Location =>
if not Context.Location.Is_Empty then
Exchange.Append (Context.Location.Query);
end if;
when Message =>
Exchange.Append
(S_Expressions.To_Atom (To_Message
(S_Expressions.To_String (Context.Code))));
when Path =>
Exchange.Append
(S_Expressions.To_Atom (Exchanges.Path (Exchange)));
when Status_Code =>
Exchange.Append (Context.Code);
end case;
end Execute;
procedure Render is new S_Expressions.Interpreter_Loop
(Sites.Exchange, Error_Context, Execute, Append);
-----------------------
-- Private Interface --
-----------------------
procedure Main_Render
(Exchange : in out Sites.Exchange;
Context : in Error_Context)
is
use type S_Expressions.Atom;
Template : S_Expressions.Caches.Cursor;
Found : Boolean;
begin
Exchange.Site.Get_Template
(S_Expressions.To_Atom ("error-page-") & Context.Code,
Template,
Found);
if not Found then
Exchange.Site.Get_Template
(S_Expressions.To_Atom ("error-page"),
Template,
Found);
if not Found then
Default_Page (Exchange, Context);
return;
end if;
end if;
Render (Template, Exchange, Context);
end Main_Render;
----------------------
-- Public Interface --
----------------------
procedure Check_Method
(Exchange : in out Sites.Exchange;
Allowed_Set : in Exchanges.Method_Set;
Allowed : out Boolean) is
begin
Allowed := Exchanges.Is_In (Exchanges.Method (Exchange), Allowed_Set);
if not Allowed then
Method_Not_Allowed (Exchange, Allowed_Set);
end if;
end Check_Method;
procedure Check_Method
(Exchange : in out Sites.Exchange;
Allowed_Methods : in Exchanges.Method_Array;
Allowed : out Boolean) is
begin
Check_Method (Exchange, Exchanges.To_Set (Allowed_Methods), Allowed);
end Check_Method;
procedure Check_Method
(Exchange : in out Sites.Exchange;
Allowed_Method : in Exchanges.Known_Method;
Allowed : out Boolean) is
begin
Check_Method (Exchange, (1 => Allowed_Method), Allowed);
end Check_Method;
procedure Method_Not_Allowed
(Exchange : in out Sites.Exchange;
Allow : in Exchanges.Method_Set)
is
Context : constant Error_Context
:= (Code => S_Expressions.To_Atom ("405"),
Location => <>);
begin
Exchanges.Method_Not_Allowed (Exchange, Allow);
Main_Render (Exchange, Context);
end Method_Not_Allowed;
procedure Not_Found (Exchange : in out Sites.Exchange) is
Context : constant Error_Context
:= (Code => S_Expressions.To_Atom ("404"),
Location => <>);
begin
Exchanges.Not_Found (Exchange);
Main_Render (Exchange, Context);
end Not_Found;
procedure Permanent_Redirect
(Exchange : in out Sites.Exchange;
Location : in S_Expressions.Atom)
is
Context : constant Error_Context
:= (Code => S_Expressions.To_Atom ("301"),
Location => S_Expressions.Atom_Ref_Constructors.Create (Location));
begin
Exchange.Permanent_Redirect (Context.Location);
Main_Render (Exchange, Context);
end Permanent_Redirect;
procedure See_Other
(Exchange : in out Sites.Exchange;
Location : in S_Expressions.Atom)
is
Context : constant Error_Context
:= (Code => S_Expressions.To_Atom ("303"),
Location => S_Expressions.Atom_Ref_Constructors.Create (Location));
begin
Exchange.See_Other (Context.Location);
Main_Render (Exchange, Context);
end See_Other;
end Natools.Web.Error_Pages;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014-2015, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.Caches;
with Natools.S_Expressions.Lockable;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.Static_Maps.Web.Error_Pages;
with Natools.Web.Fallback_Render;
package body Natools.Web.Error_Pages is
procedure Append
(Exchange : in out Sites.Exchange;
Context : in Error_Context;
Data : in S_Expressions.Atom);
procedure Default_Page
(Exchange : in out Sites.Exchange;
Context : in Error_Context);
procedure Execute
(Exchange : in out Sites.Exchange;
Context : in Error_Context;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Render is new S_Expressions.Interpreter_Loop
(Sites.Exchange, Error_Context, Execute, Append);
-------------------------
-- Error Page Renderer --
-------------------------
procedure Append
(Exchange : in out Sites.Exchange;
Context : in Error_Context;
Data : in S_Expressions.Atom)
is
pragma Unreferenced (Context);
begin
Exchange.Append (Data);
end Append;
procedure Default_Page
(Exchange : in out Sites.Exchange;
Context : in Error_Context)
is
begin
Exchange.Append (S_Expressions.To_Atom ("<html><head><title>Error "));
Exchange.Append (Context.Code);
Exchange.Append
(S_Expressions.To_Atom ("</title></head><body><h1>Error "));
Exchange.Append (Context.Code);
Exchange.Append (S_Expressions.To_Atom ("</h1><p>"));
Exchange.Append
(S_Expressions.To_Atom
(Natools.Static_Maps.Web.Error_Pages.To_Message
(S_Expressions.To_String (Context.Code))));
Exchange.Append (S_Expressions.To_Atom ("</p></body></html>"));
end Default_Page;
procedure Execute
(Exchange : in out Sites.Exchange;
Context : in Error_Context;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
procedure Re_Enter
(Exchange : in out Sites.Exchange;
Expression : in out S_Expressions.Lockable.Descriptor'Class);
procedure Re_Enter
(Exchange : in out Sites.Exchange;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render (Expression, Exchange, Context);
end Re_Enter;
use Natools.Static_Maps.Web.Error_Pages;
begin
case To_Command (S_Expressions.To_String (Name)) is
when Unknown_Command =>
Fallback_Render
(Exchange, Name, Arguments,
"error page", Re_Enter'Access);
when Location =>
if not Context.Location.Is_Empty then
Exchange.Append (Context.Location.Query);
end if;
when Message =>
Exchange.Append
(S_Expressions.To_Atom (To_Message
(S_Expressions.To_String (Context.Code))));
when Path =>
Exchange.Append
(S_Expressions.To_Atom (Exchanges.Path (Exchange)));
when Status_Code =>
Exchange.Append (Context.Code);
end case;
end Execute;
-----------------------
-- Private Interface --
-----------------------
procedure Main_Render
(Exchange : in out Sites.Exchange;
Context : in Error_Context)
is
use type S_Expressions.Atom;
Template : S_Expressions.Caches.Cursor;
Found : Boolean;
begin
Exchange.Site.Get_Template
(S_Expressions.To_Atom ("error-page-") & Context.Code,
Template,
Found);
if not Found then
Exchange.Site.Get_Template
(S_Expressions.To_Atom ("error-page"),
Template,
Found);
if not Found then
Default_Page (Exchange, Context);
return;
end if;
end if;
Render (Template, Exchange, Context);
end Main_Render;
----------------------
-- Public Interface --
----------------------
procedure Check_Method
(Exchange : in out Sites.Exchange;
Allowed_Set : in Exchanges.Method_Set;
Allowed : out Boolean) is
begin
Allowed := Exchanges.Is_In (Exchanges.Method (Exchange), Allowed_Set);
if not Allowed then
Method_Not_Allowed (Exchange, Allowed_Set);
end if;
end Check_Method;
procedure Check_Method
(Exchange : in out Sites.Exchange;
Allowed_Methods : in Exchanges.Method_Array;
Allowed : out Boolean) is
begin
Check_Method (Exchange, Exchanges.To_Set (Allowed_Methods), Allowed);
end Check_Method;
procedure Check_Method
(Exchange : in out Sites.Exchange;
Allowed_Method : in Exchanges.Known_Method;
Allowed : out Boolean) is
begin
Check_Method (Exchange, (1 => Allowed_Method), Allowed);
end Check_Method;
procedure Method_Not_Allowed
(Exchange : in out Sites.Exchange;
Allow : in Exchanges.Method_Set)
is
Context : constant Error_Context
:= (Code => S_Expressions.To_Atom ("405"),
Location => <>);
begin
Exchanges.Method_Not_Allowed (Exchange, Allow);
Main_Render (Exchange, Context);
end Method_Not_Allowed;
procedure Not_Found (Exchange : in out Sites.Exchange) is
Context : constant Error_Context
:= (Code => S_Expressions.To_Atom ("404"),
Location => <>);
begin
Exchanges.Not_Found (Exchange);
Main_Render (Exchange, Context);
end Not_Found;
procedure Permanent_Redirect
(Exchange : in out Sites.Exchange;
Location : in S_Expressions.Atom)
is
Context : constant Error_Context
:= (Code => S_Expressions.To_Atom ("301"),
Location => S_Expressions.Atom_Ref_Constructors.Create (Location));
begin
Exchange.Permanent_Redirect (Context.Location);
Main_Render (Exchange, Context);
end Permanent_Redirect;
procedure See_Other
(Exchange : in out Sites.Exchange;
Location : in S_Expressions.Atom)
is
Context : constant Error_Context
:= (Code => S_Expressions.To_Atom ("303"),
Location => S_Expressions.Atom_Ref_Constructors.Create (Location));
begin
Exchange.See_Other (Context.Location);
Main_Render (Exchange, Context);
end See_Other;
end Natools.Web.Error_Pages;
|
use the new fallback render procedure to provide common commands
|
error_pages: use the new fallback render procedure to provide common commands
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
b064f4596e0b207402ce52c350c4fab004bbd115
|
src/security-policies-roles.ads
|
src/security-policies-roles.ads
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based 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.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
-- In this policy, users are assigned one or several roles and permissions are
-- associated with roles. A permission is granted if the user has one of the roles required
-- by the permission.
--
-- === Policy creation ===
-- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Roles.Role_Policy_Access;
--
-- Create the role policy and register it in the policy manager as follows:
--
-- Policy := new Role_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- A role is represented by a name in security configuration files. A role based permission
-- is associated with a list of roles. The permission is granted if the user has one of these
-- roles. When the role based policy is registered in the policy manager, the following
-- XML configuration is used:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <security-role>
-- <role-name>manager</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt>
-- It defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
--
-- Each role is identified by a name in the configuration file. It is represented by
-- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt>
-- is represented as an integer with a limit of 64 different roles.
--
-- === Assigning roles to users ===
-- A <tt>Security_Context</tt> must be associated with a set of roles before checking the
-- permission. This is done by using the <tt>Set_Role_Context</tt> operation:
--
-- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin");
--
package Security.Policies.Roles is
NAME : constant String := "Role-Policy";
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- ------------------------------
-- Role principal context
-- ------------------------------
-- The <tt>Role_Principal_Context</tt> interface must be implemented by the user
-- <tt>Principal</tt> to be able to use the role based policy. The role based policy
-- controller will first check that the <tt>Principal</tt> implements that interface.
-- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user.
type Role_Principal_Context is limited interface;
function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract;
-- ------------------------------
-- Policy context
-- ------------------------------
-- The <b>Role_Policy_Context</b> gives security context information that the role
-- based policy can use to verify the permission.
type Role_Policy_Context is new Policy_Context with record
Roles : Role_Map;
end record;
type Role_Policy_Context_Access is access all Role_Policy_Context'Class;
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map);
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in String);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
type Role_Policy_Access is access all Role_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in Role_Policy) return String;
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
-- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by
-- its name and multiple roles are separated by ','.
-- Raises Invalid_Name if a role was not found.
procedure Set_Roles (Manager : in Role_Policy;
Roles : in String;
Into : out Role_Map);
-- Setup the XML parser to read the <b>role-permission</b> description.
overriding
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finalize the policy manager.
overriding
procedure Finalize (Policy : in out Role_Policy);
-- Get the role policy associated with the given policy manager.
-- Returns the role policy instance or null if it was not registered in the policy manager.
function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return Role_Policy_Access;
private
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Name_Array;
Next_Role : Role_Type := Role_Type'First;
end record;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : Role_Type_Array (1 .. Integer (Role_Type'Last));
Count : Natural := 0;
Manager : Role_Policy_Access;
end record;
end Security.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based 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.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
-- In this policy, users are assigned one or several roles and permissions are
-- associated with roles. A permission is granted if the user has one of the roles required
-- by the permission.
--
-- === Policy creation ===
-- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Roles.Role_Policy_Access;
--
-- Create the role policy and register it in the policy manager as follows:
--
-- Policy := new Role_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- A role is represented by a name in security configuration files. A role based permission
-- is associated with a list of roles. The permission is granted if the user has one of these
-- roles. When the role based policy is registered in the policy manager, the following
-- XML configuration is used:
--
-- <policy-rules>
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <security-role>
-- <role-name>manager</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
-- ...
-- </policy-rules>
--
-- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt>
-- It defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
--
-- Each role is identified by a name in the configuration file. It is represented by
-- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt>
-- is represented as an integer with a limit of 64 different roles.
--
-- === Assigning roles to users ===
-- A <tt>Security_Context</tt> must be associated with a set of roles before checking the
-- permission. This is done by using the <tt>Set_Role_Context</tt> operation:
--
-- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin");
--
package Security.Policies.Roles is
NAME : constant String := "Role-Policy";
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- ------------------------------
-- Role principal context
-- ------------------------------
-- The <tt>Role_Principal_Context</tt> interface must be implemented by the user
-- <tt>Principal</tt> to be able to use the role based policy. The role based policy
-- controller will first check that the <tt>Principal</tt> implements that interface.
-- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user.
type Role_Principal_Context is limited interface;
function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract;
-- ------------------------------
-- Policy context
-- ------------------------------
-- The <b>Role_Policy_Context</b> gives security context information that the role
-- based policy can use to verify the permission.
type Role_Policy_Context is new Policy_Context with record
Roles : Role_Map;
end record;
type Role_Policy_Context_Access is access all Role_Policy_Context'Class;
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map);
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in String);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
type Role_Policy_Access is access all Role_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in Role_Policy) return String;
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
-- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by
-- its name and multiple roles are separated by ','.
-- Raises Invalid_Name if a role was not found.
procedure Set_Roles (Manager : in Role_Policy;
Roles : in String;
Into : out Role_Map);
-- Setup the XML parser to read the <b>role-permission</b> description.
overriding
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finalize the policy manager.
overriding
procedure Finalize (Policy : in out Role_Policy);
-- Get the role policy associated with the given policy manager.
-- Returns the role policy instance or null if it was not registered in the policy manager.
function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return Role_Policy_Access;
private
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Name_Array;
Next_Role : Role_Type := Role_Type'First;
end record;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : Role_Type_Array (1 .. Integer (Role_Type'Last));
Count : Natural := 0;
Manager : Role_Policy_Access;
end record;
end Security.Policies.Roles;
|
Fix the XML documentation
|
Fix the XML documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
892b114cfcf08d889547cca5cd2a5856d94b44bf
|
awa/src/awa-permissions-controllers.ads
|
awa/src/awa-permissions-controllers.ads
|
-----------------------------------------------------------------------
-- awa-permissions-controllers -- Permission controllers
-- 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 Security.Contexts;
with Security.Controllers;
package AWA.Permissions.Controllers is
-- ------------------------------
-- Security Controller
-- ------------------------------
-- The <b>Entity_Controller</b> implements an entity based permission check.
-- The controller is configured through an XML description. It uses an SQL statement
-- to verify that a permission is granted.
--
-- The SQL query can use the following query parameters:
--
-- <dl>
-- <dt>entity_type</dt>
-- <dd>The entity type identifier defined by the entity permission</dd>
-- <dt>entity_id</dt>
-- <dd>The entity identifier which is associated with an <b>ACL</b> entry to check</dd>
-- <dt>user_id</dt>
-- <dd>The user identifier</dd>
-- </dl>
type Entity_Controller (Len : Positive) is
limited new Security.Controllers.Controller with record
SQL : String (1 .. Len);
Entity : ADO.Entity_Type;
end record;
type Entity_Controller_Access is access all Entity_Controller'Class;
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access a database entity. The security context contains some
-- information about the entity to check and the permission controller will use an
-- SQL statement to verify the permission.
function Has_Permission (Handler : in Entity_Controller;
Context : in Security.Contexts.Security_Context'Class)
return Boolean;
end AWA.Permissions.Controllers;
|
-----------------------------------------------------------------------
-- awa-permissions-controllers -- Permission controllers
-- 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.Contexts;
with Security.Controllers;
package AWA.Permissions.Controllers is
-- ------------------------------
-- Security Controller
-- ------------------------------
-- The <b>Entity_Controller</b> implements an entity based permission check.
-- The controller is configured through an XML description. It uses an SQL statement
-- to verify that a permission is granted.
--
-- The SQL query can use the following query parameters:
--
-- <dl>
-- <dt>entity_type</dt>
-- <dd>The entity type identifier defined by the entity permission</dd>
-- <dt>entity_id</dt>
-- <dd>The entity identifier which is associated with an <b>ACL</b> entry to check</dd>
-- <dt>user_id</dt>
-- <dd>The user identifier</dd>
-- </dl>
type Entity_Controller (Len : Positive) is
limited new Security.Controllers.Controller with record
SQL : String (1 .. Len);
Entity : ADO.Entity_Type;
end record;
type Entity_Controller_Access is access all Entity_Controller'Class;
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access a database entity. The security context contains some
-- information about the entity to check and the permission controller will use an
-- SQL statement to verify the permission.
overriding
function Has_Permission (Handler : in Entity_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
end AWA.Permissions.Controllers;
|
Fix Has_Permission to have the Permission object
|
Fix Has_Permission to have the Permission object
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f32f88bb259bdc44367e882c676a00939bcee4ba
|
awa/plugins/awa-workspaces/src/awa-workspaces.ads
|
awa/plugins/awa-workspaces/src/awa-workspaces.ads
|
-----------------------------------------------------------------------
-- awa-workspaces -- Module workspaces
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The *workspaces* plugin defines a workspace area for other plugins.
-- The workspace is intended to link together all the data objects that an application
-- manages for a given user or group of users. A workspace is a possible mechanism
-- to provide and implement multi-tenancy in a web application. By using the workspace plugin,
-- application data from different customers can be kept separate from each other in the
-- same database.
--
-- == Ada Beans ==
-- @include workspaces.xml
--
-- == Data Model ==
-- [images/awa_workspace_model.png]
--
package AWA.Workspaces is
end AWA.Workspaces;
|
-----------------------------------------------------------------------
-- awa-workspaces -- Module workspaces
-- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The *workspaces* plugin defines a workspace area for other plugins.
-- The workspace is intended to link together all the data objects that an application
-- manages for a given user or group of users. A workspace is a possible mechanism
-- to provide and implement multi-tenancy in a web application. By using the workspace plugin,
-- application data from different customers can be kept separate from each other in the
-- same database.
--
-- @include awa-workspaces-modules.ads
--
-- == Ada Beans ==
-- @include workspaces.xml
--
-- == Data Model ==
-- [images/awa_workspace_model.png]
--
package AWA.Workspaces is
end AWA.Workspaces;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b280a78468e9f34a037d04078163ab55274cb759
|
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
|
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-tags-modules-tests -- Unit tests for tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Tags.Beans;
package body AWA.Tags.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Tags.Modules");
function Create_Tag_List_Bean (Module : in Tag_Module_Access)
return AWA.Tags.Beans.Tag_List_Bean_Access;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag",
Test_Add_Tag'Access);
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag",
Test_Remove_Tag'Access);
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Update_Tags",
Test_Remove_Tag'Access);
end Add_Tests;
function Create_Tag_List_Bean (Module : in Tag_Module_Access)
return AWA.Tags.Beans.Tag_List_Bean_Access is
Bean : constant Util.Beans.Basic.Readonly_Bean_Access
:= AWA.Tags.Beans.Create_Tag_List_Bean (Module);
begin
return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Test tag creation.
-- ------------------------------
procedure Test_Add_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
-- Create a tag.
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null");
end;
end Test_Add_Tag;
-- ------------------------------
-- Test tag removal.
-- ------------------------------
procedure Test_Remove_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null");
end;
end Test_Remove_Tag;
-- ------------------------------
-- Test tag creation and removal.
-- ------------------------------
procedure Test_Update_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
Tags : Util.Strings.Vectors.Vector;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
List.Set_Value ("permission", Util.Beans.Objects.To_Object (String '("workspace-create")));
-- Add 3 tags.
Tags.Append ("user-tag-1");
Tags.Append ("user-tag-2");
Tags.Append ("user-tag-3");
List.Set_Added (Tags);
List.Update_Tags (User.Get_Id);
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 3, Integer (List.Get_Count), "Invalid number of tags");
-- Remove a tag that was not created.
Tags.Append ("user-tag-4");
List.Set_Deleted (Tags);
Tags.Clear;
Tags.Append ("user-tag-5");
List.Set_Added (Tags);
List.Update_Tags (User.Get_Id);
-- 'user-tag-5' is the only tag that should exist now.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null");
end;
end Test_Update_Tag;
end AWA.Tags.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-tags-modules-tests -- Unit tests for tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Tags.Beans;
package body AWA.Tags.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Tags.Modules");
function Create_Tag_List_Bean (Module : in Tag_Module_Access)
return AWA.Tags.Beans.Tag_List_Bean_Access;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag",
Test_Add_Tag'Access);
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag",
Test_Remove_Tag'Access);
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Update_Tags",
Test_Remove_Tag'Access);
end Add_Tests;
function Create_Tag_List_Bean (Module : in Tag_Module_Access)
return AWA.Tags.Beans.Tag_List_Bean_Access is
Bean : constant Util.Beans.Basic.Readonly_Bean_Access
:= AWA.Tags.Beans.Create_Tag_List_Bean (Module);
begin
return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Test tag creation.
-- ------------------------------
procedure Test_Add_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
-- Create a tag.
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null");
end;
end Test_Add_Tag;
-- ------------------------------
-- Test tag removal.
-- ------------------------------
procedure Test_Remove_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null");
end;
end Test_Remove_Tag;
-- ------------------------------
-- Test tag creation and removal.
-- ------------------------------
procedure Test_Update_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
Tags : Util.Strings.Vectors.Vector;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
List.Set_Value ("permission",
Util.Beans.Objects.To_Object (String '("workspace-create")));
-- Add 3 tags.
Tags.Append ("user-tag-1");
Tags.Append ("user-tag-2");
Tags.Append ("user-tag-3");
List.Set_Added (Tags);
List.Update_Tags (User.Get_Id);
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 3, Integer (List.Get_Count), "Invalid number of tags");
-- Remove a tag that was not created.
Tags.Append ("user-tag-4");
List.Set_Deleted (Tags);
Tags.Clear;
Tags.Append ("user-tag-5");
List.Set_Added (Tags);
List.Update_Tags (User.Get_Id);
-- 'user-tag-5' is the only tag that should exist now.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null");
end;
end Test_Update_Tag;
end AWA.Tags.Modules.Tests;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0349098a92a1f8d1954979f77ffd30e115001a5c
|
posix-directory.adb
|
posix-directory.adb
|
with C_String;
with Interfaces.C;
package body POSIX.Directory is
--
-- Change_By_Descriptor.
--
procedure Change_By_Descriptor
(Descriptor : in File.Valid_Descriptor_t;
Error_Value : out Error.Error_t)
is
function Fchdir (Descriptor : in File.Valid_Descriptor_t)
return Error.Return_Value_t;
pragma Import (C, Fchdir, "fchdir");
begin
if Fchdir (Descriptor) = -1 then
Error_Value := Error.Get_Error;
else
Error_Value := Error.Error_None;
end if;
end Change_By_Descriptor;
--
-- Change_By_Name.
--
procedure Change_By_Name
(Path : in String;
Error_Value : out Error.Error_t)
is
Descriptor : File.Descriptor_t;
Error_Local : Error.Error_t;
begin
File.Open_Read_Only
(File_Name => Path,
Non_Blocking => False,
Descriptor => Descriptor,
Error_Value => Error_Local);
if Error_Local = Error.Error_None then
Change_By_Descriptor
(Descriptor => Descriptor,
Error_Value => Error_Value);
File.Close
(Descriptor => Descriptor,
Error_Value => Error_Local);
if Error_Local /= Error.Error_None then
Error_Value := Error_Local;
end if;
else
Error_Value := Error_Local;
end if;
end Change_By_Name;
--
-- Create directory.
--
function Create_Boundary
(Name : in String;
Mode : in Permissions.Mode_t) return Error.Return_Value_t
--# global in Errno.Errno_Value;
--# return R =>
--# ((R = 0) -> (Error.Get_Error (Errno.Errno_Value) = Error.Error_None)) or
--# ((R = -1) -> (Error.Get_Error (Errno.Errno_Value) /= Error.Error_None));
is
C_Name : aliased Interfaces.C.char_array := Interfaces.C.To_C (Name);
function Mkdir
(Name : in C_String.String_Not_Null_Ptr_t;
Mode : in Permissions.Mode_t) return Error.Return_Value_t;
pragma Import (C, Mkdir, "mkdir");
begin
return Mkdir
(Name => C_String.To_C_String (C_Name'Unchecked_Access),
Mode => Mode);
end Create_Boundary;
procedure Create
(Name : in String;
Mode : in Permissions.Mode_t;
Error_Value : out Error.Error_t) is
begin
case Create_Boundary (Name, Mode) is
when 0 => Error_Value := Error.Get_Error;
when -1 => Error_Value := Error.Error_None;
end case;
end Create;
--
-- Remove empty directory.
--
function Remove_Boundary (Name : in String) return Error.Return_Value_t
--# global in Errno.Errno_Value;
--# return R =>
--# ((R = 0) -> (Error.Get_Error (Errno.Errno_Value) = Error.Error_None)) or
--# ((R = -1) -> (Error.Get_Error (Errno.Errno_Value) /= Error.Error_None));
is
C_Name : aliased Interfaces.C.char_array := Interfaces.C.To_C (Name);
function Rmdir (Name : in C_String.String_Not_Null_Ptr_t)
return Error.Return_Value_t;
pragma Import (C, Rmdir, "rmdir");
begin
return Rmdir (C_String.To_C_String (C_Name'Unchecked_Access));
end Remove_Boundary;
procedure Remove
(Name : in String;
Error_Value : out Error.Error_t) is
begin
case Remove_Boundary (Name) is
when 0 => Error_Value := Error.Get_Error;
when -1 => Error_Value := Error.Error_None;
end case;
end Remove;
end POSIX.Directory;
|
with C_String;
with Interfaces.C;
package body POSIX.Directory is
--
-- Change_By_Descriptor.
--
procedure Change_By_Descriptor
(Descriptor : in File.Valid_Descriptor_t;
Error_Value : out Error.Error_t)
is
function Fchdir (Descriptor : in File.Valid_Descriptor_t)
return Error.Return_Value_t;
pragma Import (C, Fchdir, "fchdir");
begin
if Fchdir (Descriptor) = -1 then
Error_Value := Error.Get_Error;
else
Error_Value := Error.Error_None;
end if;
end Change_By_Descriptor;
--
-- Change_By_Name.
--
procedure Change_By_Name
(Path : in String;
Error_Value : out Error.Error_t)
is
Descriptor : File.Descriptor_t;
Error_Local : Error.Error_t;
begin
File.Open_Read_Only
(File_Name => Path,
Non_Blocking => False,
Descriptor => Descriptor,
Error_Value => Error_Local);
if Error_Local = Error.Error_None then
Change_By_Descriptor
(Descriptor => Descriptor,
Error_Value => Error_Value);
File.Close
(Descriptor => Descriptor,
Error_Value => Error_Local);
if Error_Local /= Error.Error_None then
Error_Value := Error_Local;
end if;
else
Error_Value := Error_Local;
end if;
end Change_By_Name;
--
-- Create directory.
--
function Create_Boundary
(Name : in String;
Mode : in Permissions.Mode_t) return Error.Return_Value_t
--# global in Errno.Errno_Value;
--# return R =>
--# ((R = 0) -> (Error.Get_Error (Errno.Errno_Value) = Error.Error_None)) or
--# ((R = -1) -> (Error.Get_Error (Errno.Errno_Value) /= Error.Error_None));
is
C_Name : aliased Interfaces.C.char_array := Interfaces.C.To_C (Name);
function Mkdir
(Name : in C_String.String_Not_Null_Ptr_t;
Mode : in Permissions.Mode_t) return Error.Return_Value_t;
pragma Import (C, Mkdir, "mkdir");
begin
return Mkdir
(Name => C_String.To_C_String (C_Name'Unchecked_Access),
Mode => Mode);
end Create_Boundary;
procedure Create
(Name : in String;
Mode : in Permissions.Mode_t;
Error_Value : out Error.Error_t) is
begin
case Create_Boundary (Name, Mode) is
when 0 => Error_Value := Error.Error_None;
when -1 => Error_Value := Error.Get_Error;
end case;
end Create;
--
-- Remove empty directory.
--
function Remove_Boundary (Name : in String) return Error.Return_Value_t
--# global in Errno.Errno_Value;
--# return R =>
--# ((R = 0) -> (Error.Get_Error (Errno.Errno_Value) = Error.Error_None)) or
--# ((R = -1) -> (Error.Get_Error (Errno.Errno_Value) /= Error.Error_None));
is
C_Name : aliased Interfaces.C.char_array := Interfaces.C.To_C (Name);
function Rmdir (Name : in C_String.String_Not_Null_Ptr_t)
return Error.Return_Value_t;
pragma Import (C, Rmdir, "rmdir");
begin
return Rmdir (C_String.To_C_String (C_Name'Unchecked_Access));
end Remove_Boundary;
procedure Remove
(Name : in String;
Error_Value : out Error.Error_t) is
begin
case Remove_Boundary (Name) is
when 0 => Error_Value := Error.Error_None;
when -1 => Error_Value := Error.Get_Error;
end case;
end Remove;
end POSIX.Directory;
|
Fix return value handling.
|
Fix return value handling.
|
Ada
|
isc
|
io7m/coreland-posix-ada,io7m/coreland-posix-ada,io7m/coreland-posix-ada
|
97a90a43d6d7514a9a20f8f54afd6fc3954a0893
|
awa/samples/src/atlas-server.adb
|
awa/samples/src/atlas-server.adb
|
-----------------------------------------------------------------------
-- Atlas-server -- Application server
-- Copyright (C) 2011 XXX
-- Written by XXX (XXX)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Exceptions;
with ASF.Server.Web;
with Atlas.Applications;
procedure Atlas.Server is
CONTEXT_PATH : constant String := "/atlas";
App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application;
WS : ASF.Server.Web.AWS_Container;
begin
Atlas.Applications.Initialize (App);
WS.Register_Application (CONTEXT_PATH, App.all'Access);
WS.Start;
delay 365.0 * 24.0 * 3600.0;
App.Close;
exception
when E: others =>
Ada.Text_IO.Put_Line ("Exception in server: " &
Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E));
end Atlas.Server;
|
-----------------------------------------------------------------------
-- Atlas-server -- Application server
-- Copyright (C) 2011 XXX
-- Written by XXX (XXX)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Exceptions;
with ASF.Server.Web;
with Util.Log.Loggers;
with Atlas.Applications;
procedure Atlas.Server is
CONTEXT_PATH : constant String := "/atlas";
App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application;
Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server");
WS : ASF.Server.Web.AWS_Container;
begin
Atlas.Applications.Initialize (App);
WS.Register_Application (CONTEXT_PATH, App.all'Access);
Log.Info ("Connect you browser to: http://localhost:8080/atlas/index.html");
WS.Start;
delay 365.0 * 24.0 * 3600.0;
App.Close;
exception
when E: others =>
Ada.Text_IO.Put_Line ("Exception in server: " &
Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E));
end Atlas.Server;
|
Add a log to indicate the main URL to connect to
|
Add a log to indicate the main URL to connect to
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
cff850651f4942a6f08d65abd1ffbe3a5e8304e8
|
src/ado-schemas.ads
|
src/ado-schemas.ads
|
-----------------------------------------------------------------------
-- ado.schemas -- Database Schemas
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Containers;
with Util.Strings;
package ADO.Schemas is
type Member_Names is array (Natural range <>) of Util.Strings.Name_Access;
type Class_Mapping (Count : Natural) is tagged record
Table : Util.Strings.Name_Access;
-- Name : Natural := 0;
Members : Member_Names (1 .. Count);
end record;
type Class_Mapping_Access is access constant Class_Mapping'Class;
-- Get the hash value associated with the class mapping.
function Hash (Mapping : Class_Mapping_Access) return Ada.Containers.Hash_Type;
-- Get the Ada type mapping for the column
type Column_Type is
(
T_UNKNOWN,
-- Boolean column
T_BOOLEAN,
T_TINYINT,
T_SMALLINT,
T_INTEGER,
T_LONG_INTEGER,
T_FLOAT,
T_DOUBLE,
T_DECIMAL,
T_ENUM,
T_SET,
T_TIME,
T_YEAR,
T_DATE,
T_DATE_TIME,
T_TIMESTAMP,
T_CHAR,
T_VARCHAR,
T_BLOB
);
-- ------------------------------
-- Column Representation
-- ------------------------------
-- Describes a column in a table.
type Column_Definition is private;
-- Get the column name
function Get_Name (Column : Column_Definition) return String;
-- Get the column type
function Get_Type (Column : Column_Definition) return Column_Type;
-- Get the default column value
function Get_Default (Column : Column_Definition) return String;
-- Get the column collation (for string based columns)
function Get_Collation (Column : Column_Definition) return String;
-- Check whether the column can be null
function Is_Null (Column : Column_Definition) return Boolean;
-- Check whether the column is an unsigned number
function Is_Unsigned (Column : Column_Definition) return Boolean;
-- Returns true if the column can hold a binary string
function Is_Binary (Column : Column_Definition) return Boolean;
-- Get the column length
function Get_Size (Column : Column_Definition) return Natural;
-- ------------------------------
-- Column iterator
-- ------------------------------
type Column_Cursor is private;
-- Returns true if the iterator contains more column
function Has_Element (Cursor : Column_Cursor) return Boolean;
-- Move to the next column
procedure Next (Cursor : in out Column_Cursor);
-- Get the current column definition
function Element (Cursor : Column_Cursor) return Column_Definition;
-- ------------------------------
-- Table Representation
-- ------------------------------
-- Describes a table in the database. The table contains a list
-- of columns described by Column_Definition.
type Table_Definition is private;
-- Get the table name
function Get_Name (Table : Table_Definition) return String;
-- Get the column iterator
function Get_Columns (Table : Table_Definition) return Column_Cursor;
-- Find the column having the given name
function Find_Column (Table : Table_Definition;
Name : String) return Column_Definition;
-- ------------------------------
-- Table iterator
-- ------------------------------
type Table_Cursor is private;
-- Returns true if the iterator contains more tables
function Has_Element (Cursor : Table_Cursor) return Boolean;
-- Move to the next column
procedure Next (Cursor : in out Table_Cursor);
-- Get the current table definition
function Element (Cursor : Table_Cursor) return Table_Definition;
-- ------------------------------
-- Database Schema
-- ------------------------------
type Schema_Definition is limited private;
-- Find a table knowing its name
function Find_Table (Schema : Schema_Definition;
Name : String) return Table_Definition;
function Get_Tables (Schema : Schema_Definition) return Table_Cursor;
private
use Ada.Strings.Unbounded;
type Column;
type Column_Definition is access all Column;
type Table;
type Table_Definition is access all Table;
type Schema;
type Schema_Access is access all Schema;
type Schema_Definition is new Ada.Finalization.Limited_Controlled with record
Schema : Schema_Access;
end record;
procedure Finalize (Schema : in out Schema_Definition);
type Column_Cursor is record
Current : Column_Definition;
end record;
type Table_Cursor is record
Current : Table_Definition;
end record;
type Column is record
Next_Column : Column_Definition;
Table : Table_Definition;
Name : Unbounded_String;
Default : Unbounded_String;
Collation : Unbounded_String;
Col_Type : Column_Type := T_VARCHAR;
Size : Natural := 0;
Is_Null : Boolean := False;
Is_Binary : Boolean := False;
Is_Unsigned : Boolean := False;
end record;
type Table is record
Name : Unbounded_String;
First_Column : Column_Definition;
Next_Table : Table_Definition;
end record;
type Schema is record
-- Tables : Table_Definition;
First_Table : Table_Definition;
end record;
end ADO.Schemas;
|
-----------------------------------------------------------------------
-- ado.schemas -- Database Schemas
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Containers;
with Util.Strings;
package ADO.Schemas is
type Member_Names is array (Natural range <>) of Util.Strings.Name_Access;
type Class_Mapping (Count : Natural) is tagged record
Table : Util.Strings.Name_Access;
-- Name : Natural := 0;
Members : Member_Names (1 .. Count);
end record;
type Class_Mapping_Access is access constant Class_Mapping'Class;
-- Get the hash value associated with the class mapping.
function Hash (Mapping : Class_Mapping_Access) return Ada.Containers.Hash_Type;
-- Get the Ada type mapping for the column
type Column_Type is
(
T_UNKNOWN,
-- Boolean column
T_BOOLEAN,
T_TINYINT,
T_SMALLINT,
T_INTEGER,
T_LONG_INTEGER,
T_FLOAT,
T_DOUBLE,
T_DECIMAL,
T_ENUM,
T_SET,
T_TIME,
T_YEAR,
T_DATE,
T_DATE_TIME,
T_TIMESTAMP,
T_CHAR,
T_VARCHAR,
T_BLOB,
T_NULL
);
-- ------------------------------
-- Column Representation
-- ------------------------------
-- Describes a column in a table.
type Column_Definition is private;
-- Get the column name
function Get_Name (Column : Column_Definition) return String;
-- Get the column type
function Get_Type (Column : Column_Definition) return Column_Type;
-- Get the default column value
function Get_Default (Column : Column_Definition) return String;
-- Get the column collation (for string based columns)
function Get_Collation (Column : Column_Definition) return String;
-- Check whether the column can be null
function Is_Null (Column : Column_Definition) return Boolean;
-- Check whether the column is an unsigned number
function Is_Unsigned (Column : Column_Definition) return Boolean;
-- Returns true if the column can hold a binary string
function Is_Binary (Column : Column_Definition) return Boolean;
-- Get the column length
function Get_Size (Column : Column_Definition) return Natural;
-- ------------------------------
-- Column iterator
-- ------------------------------
type Column_Cursor is private;
-- Returns true if the iterator contains more column
function Has_Element (Cursor : Column_Cursor) return Boolean;
-- Move to the next column
procedure Next (Cursor : in out Column_Cursor);
-- Get the current column definition
function Element (Cursor : Column_Cursor) return Column_Definition;
-- ------------------------------
-- Table Representation
-- ------------------------------
-- Describes a table in the database. The table contains a list
-- of columns described by Column_Definition.
type Table_Definition is private;
-- Get the table name
function Get_Name (Table : Table_Definition) return String;
-- Get the column iterator
function Get_Columns (Table : Table_Definition) return Column_Cursor;
-- Find the column having the given name
function Find_Column (Table : Table_Definition;
Name : String) return Column_Definition;
-- ------------------------------
-- Table iterator
-- ------------------------------
type Table_Cursor is private;
-- Returns true if the iterator contains more tables
function Has_Element (Cursor : Table_Cursor) return Boolean;
-- Move to the next column
procedure Next (Cursor : in out Table_Cursor);
-- Get the current table definition
function Element (Cursor : Table_Cursor) return Table_Definition;
-- ------------------------------
-- Database Schema
-- ------------------------------
type Schema_Definition is limited private;
-- Find a table knowing its name
function Find_Table (Schema : Schema_Definition;
Name : String) return Table_Definition;
function Get_Tables (Schema : Schema_Definition) return Table_Cursor;
private
use Ada.Strings.Unbounded;
type Column;
type Column_Definition is access all Column;
type Table;
type Table_Definition is access all Table;
type Schema;
type Schema_Access is access all Schema;
type Schema_Definition is new Ada.Finalization.Limited_Controlled with record
Schema : Schema_Access;
end record;
procedure Finalize (Schema : in out Schema_Definition);
type Column_Cursor is record
Current : Column_Definition;
end record;
type Table_Cursor is record
Current : Table_Definition;
end record;
type Column is record
Next_Column : Column_Definition;
Table : Table_Definition;
Name : Unbounded_String;
Default : Unbounded_String;
Collation : Unbounded_String;
Col_Type : Column_Type := T_VARCHAR;
Size : Natural := 0;
Is_Null : Boolean := False;
Is_Binary : Boolean := False;
Is_Unsigned : Boolean := False;
end record;
type Table is record
Name : Unbounded_String;
First_Column : Column_Definition;
Next_Table : Table_Definition;
end record;
type Schema is record
-- Tables : Table_Definition;
First_Table : Table_Definition;
end record;
end ADO.Schemas;
|
Add T_NULL column type
|
Add T_NULL column type
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
40fb24bc61ed274b69c977abd7a22bc533c2b954
|
regtests/util-streams-sockets-tests.adb
|
regtests/util-streams-sockets-tests.adb
|
-----------------------------------------------------------------------
-- util-streams-sockets-tests -- Unit tests for socket streams
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.IO_Exceptions;
with Util.Test_Caller;
with Util.Streams.Texts;
with Util.Tests.Servers;
package body Util.Streams.Sockets.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Streams.Sockets");
type Test_Server is new Util.Tests.Servers.Server with record
Count : Natural := 0;
end record;
-- Process the line received by the server.
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect",
Test_Socket_Init'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write",
Test_Socket_Read'Access);
end Add_Tests;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
pragma Unreferenced (Stream, Client);
begin
if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then
Into.Count := Into.Count + 1;
end if;
end Process_Line;
-- ------------------------------
-- Test reading and writing on a socket stream.
-- ------------------------------
procedure Test_Socket_Read (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Writer : Util.Streams.Texts.Print_Stream;
Server : Test_Server;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Server.Start;
T.Assert (Server.Get_Port > 0, "The server was not started");
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
GNAT.Sockets.Port_Type (Server.Get_Port));
-- Let the server start.
delay 0.1;
-- Get a connection and write 10 lines.
Stream.Connect (Server => Addr);
Writer.Initialize (Output => Stream'Unchecked_Access,
Input => null,
Size => 1024);
for I in 1 .. 10 loop
Writer.Write ("Sending a line on the socket test-"
& Natural'Image (I) & ASCII.CR & ASCII.LF);
Writer.Flush;
end loop;
Writer.Close;
-- Stop the server and verify that 10 lines were received.
Server.Stop;
Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received");
end Test_Socket_Read;
-- ------------------------------
-- Test socket initialization.
-- ------------------------------
procedure Test_Socket_Init (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Fd : GNAT.Sockets.Socket_Type;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
80);
GNAT.Sockets.Create_Socket (Fd);
Stream.Open (Fd);
begin
Stream.Connect (Addr);
T.Assert (False, "No exception was raised");
exception
when Ada.IO_Exceptions.Use_Error =>
null;
end;
end Test_Socket_Init;
end Util.Streams.Sockets.Tests;
|
-----------------------------------------------------------------------
-- util-streams-sockets-tests -- Unit tests for socket streams
-- Copyright (C) 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.IO_Exceptions;
with Util.Test_Caller;
with Util.Streams.Texts;
with Util.Tests.Servers;
package body Util.Streams.Sockets.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Streams.Sockets");
type Test_Server is new Util.Tests.Servers.Server with record
Count : Natural := 0;
end record;
-- Process the line received by the server.
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect",
Test_Socket_Init'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write",
Test_Socket_Read'Access);
end Add_Tests;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
pragma Unreferenced (Stream, Client);
begin
if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then
Into.Count := Into.Count + 1;
end if;
end Process_Line;
-- ------------------------------
-- Test reading and writing on a socket stream.
-- ------------------------------
procedure Test_Socket_Read (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Writer : Util.Streams.Texts.Print_Stream;
Server : Test_Server;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Server.Start;
T.Assert (Server.Get_Port > 0, "The server was not started");
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
GNAT.Sockets.Port_Type (Server.Get_Port));
-- Let the server start.
delay 0.1;
-- Get a connection and write 10 lines.
Stream.Connect (Server => Addr);
Writer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024);
for I in 1 .. 10 loop
Writer.Write ("Sending a line on the socket test-"
& Natural'Image (I) & ASCII.CR & ASCII.LF);
Writer.Flush;
end loop;
Writer.Close;
-- Stop the server and verify that 10 lines were received.
Server.Stop;
Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received");
end Test_Socket_Read;
-- ------------------------------
-- Test socket initialization.
-- ------------------------------
procedure Test_Socket_Init (T : in out Test) is
Stream : aliased Sockets.Socket_Stream;
Fd : GNAT.Sockets.Socket_Type;
Addr : GNAT.Sockets.Sock_Addr_Type;
begin
Addr := (GNAT.Sockets.Family_Inet,
GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1),
80);
GNAT.Sockets.Create_Socket (Fd);
Stream.Open (Fd);
begin
Stream.Connect (Addr);
T.Assert (False, "No exception was raised");
exception
when Ada.IO_Exceptions.Use_Error =>
null;
end;
end Test_Socket_Init;
end Util.Streams.Sockets.Tests;
|
Update Print_Stream initialization
|
Update Print_Stream initialization
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c0b5149f8565c11e4b0a80636882ccb8b27cc1f8
|
src/gl/interface/gl-objects-queries.ads
|
src/gl/interface/gl-objects-queries.ads
|
--------------------------------------------------------------------------------
-- Copyright (c) 2016 onox <[email protected]>
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
with GL.Low_Level;
with GL.Objects;
package GL.Objects.Queries is
pragma Preelaborate;
type Query_Type is (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 (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 Time_Elapsed .. Any_Samples_Passed_Conservative;
subtype Timestamp_Query_Type is Query_Type range Timestamp .. Timestamp;
subtype Primitive_Query_Type is Query_Type
with Static_Predicate =>
Primitive_Query_Type in Primitives_Generated | Transform_Feedback_Primitives_Written;
subtype Occlusion_Query_Type is Query_Type
with Static_Predicate =>
Occlusion_Query_Type in Samples_Passed | Any_Samples_Passed | Any_Samples_Passed_Conservative;
subtype Time_Query_Type is Query_Type
with Static_Predicate => Time_Query_Type = Time_Elapsed;
type Query_Mode is (Wait, No_Wait, By_Region_Wait, By_Region_No_Wait);
type Query_Param is (Result, Result_Available, Result_No_Wait);
type Target_Param is (Counter_Bits, Current_Query);
type Query is new GL_Object with private;
overriding
procedure Initialize_Id (Object : in out Query);
overriding
procedure Delete_Id (Object : in out Query);
type Active_Query is tagged limited private;
type Conditional_Render is tagged limited private;
function Begin_Primitive_Query (Object : in out Query;
Target : in Primitive_Query_Type;
Index : in Natural := 0)
return Active_Query'Class;
function Begin_Occlusion_Query (Object : in out Query;
Target : in Occlusion_Query_Type)
return Active_Query'Class;
function Begin_Timer_Query (Object : in out Query;
Target : in Time_Query_Type)
return Active_Query'Class;
function Begin_Conditional_Render (Object : in out Query;
Mode : in Query_Mode)
return Conditional_Render'Class;
function Result_Available (Object : in out Query) return Boolean;
function Result_If_Available (Object : in out Query; Default_Value : Boolean)
return Boolean;
function Result_If_Available (Object : in out Query; Default_Value : Natural)
return Natural;
function Result (Object : in out Query) return Boolean;
function Result (Object : in out Query) return Natural;
function Result_Bits (Target : in Query_Type) return Natural;
procedure Record_Current_Time (Object : in out Query);
function Get_Current_Time return Long;
private
for Query_Mode use (Wait => 16#8E13#,
No_Wait => 16#8E14#,
By_Region_Wait => 16#8E15#,
By_Region_No_Wait => 16#8E16#);
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 is new GL_Object with null record;
type Active_Query is limited new Ada.Finalization.Limited_Controlled with record
Query_Object : Query;
Target : Query_Type;
Index : Natural;
end record;
overriding
procedure Initialize (Object : in out Active_Query);
overriding
procedure Finalize (Object : in out Active_Query);
type Conditional_Render is limited new Ada.Finalization.Limited_Controlled with record
Query_Object : Query;
Mode : Query_Mode;
end record;
overriding
procedure Initialize (Object : in out Conditional_Render);
overriding
procedure Finalize (Object : in out Conditional_Render);
end GL.Objects.Queries;
|
--------------------------------------------------------------------------------
-- Copyright (c) 2016 onox <[email protected]>
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
with GL.Low_Level;
with GL.Objects;
package GL.Objects.Queries is
pragma Preelaborate;
type Query_Type is (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 (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 Time_Elapsed .. Any_Samples_Passed_Conservative;
subtype Timestamp_Query_Type is Query_Type range Timestamp .. Timestamp;
subtype Primitive_Query_Type is Query_Type
with Static_Predicate =>
Primitive_Query_Type in Primitives_Generated | Transform_Feedback_Primitives_Written;
subtype Occlusion_Query_Type is Query_Type
with Static_Predicate =>
Occlusion_Query_Type in Samples_Passed | Any_Samples_Passed | Any_Samples_Passed_Conservative;
subtype Time_Query_Type is Query_Type
with Static_Predicate => Time_Query_Type = Time_Elapsed;
type Query_Mode is (Wait, No_Wait, By_Region_Wait, By_Region_No_Wait);
type Query_Param is (Result, Result_Available, Result_No_Wait);
type Target_Param is (Counter_Bits, Current_Query);
type Query is new GL_Object with private;
overriding
procedure Initialize_Id (Object : in out Query);
overriding
procedure Delete_Id (Object : in out Query);
type Active_Query is tagged limited private;
type Conditional_Render is tagged limited private;
function Begin_Primitive_Query (Object : in out Query;
Target : in Primitive_Query_Type;
Index : in Natural := 0)
return Active_Query'Class;
-- Start a primitive 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.
--
-- Primitive queries support multiple query operations; one for each
-- index. The index represents the vertex output stream used in a
-- Geometry Shader. If the target type is
-- Transform_Feedback_Primitives_Written, then the query should be
-- issued while within a transform feedback scope.
function Begin_Occlusion_Query (Object : in out Query;
Target : in Occlusion_Query_Type)
return Active_Query'Class;
-- Start an occlusion 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.
function Begin_Timer_Query (Object : in out Query;
Target : in Time_Query_Type)
return Active_Query'Class;
-- Start a timer 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.
--
-- This function is used only for queries of type Time_Elapsed.
-- 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.
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.
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#);
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 is new GL_Object with null record;
type Active_Query is limited new Ada.Finalization.Limited_Controlled with record
Query_Object : Query;
Target : Query_Type;
Index : Natural;
end record;
overriding
procedure Initialize (Object : in out Active_Query);
overriding
procedure Finalize (Object : in out Active_Query);
type Conditional_Render is limited new Ada.Finalization.Limited_Controlled with record
Query_Object : Query;
Mode : Query_Mode;
end record;
overriding
procedure Initialize (Object : in out Conditional_Render);
overriding
procedure Finalize (Object : in out Conditional_Render);
end GL.Objects.Queries;
|
Document GL.Objects.Queries a bit
|
gl: Document GL.Objects.Queries a bit
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
3740a005d283177a3415ea6eb635398601853618
|
orka/src/orka/implementation/orka-terminals.adb
|
orka/src/orka/implementation/orka-terminals.adb
|
-- 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 Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with Orka.OS;
with Orka.Strings;
package body Orka.Terminals is
Style_Codes : constant array (Style) of Natural :=
(Default => 0,
Bold => 1,
Dark => 2,
Italic => 3,
Underline => 4,
Blink => 5,
Reversed => 7,
Cross_Out => 9);
Foreground_Color_Codes : constant array (Color) of Natural :=
(Default => 0,
Grey => 30,
Red => 31,
Green => 32,
Yellow => 33,
Blue => 34,
Magenta => 35,
Cyan => 36,
White => 37);
Background_Color_Codes : constant array (Color) of Natural :=
(Default => 0,
Grey => 40,
Red => 41,
Green => 42,
Yellow => 43,
Blue => 44,
Magenta => 45,
Cyan => 46,
White => 47);
package L1 renames Ada.Characters.Latin_1;
package SF renames Ada.Strings.Fixed;
Reset : constant String := L1.ESC & "[0m";
function Sequence (Code : Natural) return String is
Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both);
begin
return (if Code /= 0 then L1.ESC & "[" & Image & "m" else "");
end Sequence;
function Colorize (Text : String; Foreground, Background : Color := Default;
Attribute : Style := Default) return String is
FG : constant String := Sequence (Foreground_Color_Codes (Foreground));
BG : constant String := Sequence (Background_Color_Codes (Background));
ST : constant String := Sequence (Style_Codes (Attribute));
begin
return Reset & FG & BG & ST & Text & Reset;
end Colorize;
-----------------------------------------------------------------------------
Time_Zero : Duration := 0.0;
procedure Set_Time_Zero (Time : Duration) is
begin
Time_Zero := Time;
end Set_Time_Zero;
Day_In_Seconds : constant := 24.0 * 60.0 * 60.0;
function Time_Image return String is
Seconds_Since_Zero : Duration := Orka.OS.Monotonic_Clock - Time_Zero;
Days_Since_Zero : Natural := 0;
begin
while Seconds_Since_Zero > Day_In_Seconds loop
Seconds_Since_Zero := Seconds_Since_Zero - Day_In_Seconds;
Days_Since_Zero := Days_Since_Zero + 1;
end loop;
declare
Seconds_Rounded : constant Natural :=
Natural (Duration'Max (0.0, Seconds_Since_Zero - 0.5));
Hour : constant Natural := Seconds_Rounded / 3600;
Minute : constant Natural := (Seconds_Rounded mod 3600) / 60;
Second : constant Natural := Seconds_Rounded mod 60;
Sub_Second : constant Duration :=
Seconds_Since_Zero - Duration (Hour * 3600 + Minute * 60 + Second);
-- Remove first character (space) from ' hhmmss' image and then pad it to six digits
Image1 : constant String := Natural'Image
((Days_Since_Zero * 24 + Hour) * 1e4 + Minute * 1e2 + Second);
Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0');
-- Insert ':' characters to get 'hh:mm:ss'
Image3 : constant String := SF.Insert (Image2, 5, ":");
Image4 : constant String := SF.Insert (Image3, 3, ":");
-- Take image without first character (space) and then pad it to six digits
Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6));
Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0');
begin
return Image4 & "." & Image6;
end;
end Time_Image;
function Format (Value : Duration; Fore, Aft : Positive) return String is
package SF renames Ada.Strings.Fixed;
Aft_Shift : constant Positive := 10 ** Aft;
New_Value : constant Duration := Duration (Integer (Value * Aft_Shift)) / Aft_Shift;
S1 : constant String := SF.Trim (New_Value'Image, Ada.Strings.Both);
Index_Decimal : constant Natural := SF.Index (S1, ".");
-- Following code assumes that Aft >= 1 (If Aft = 0 then Aft must
-- be decremented to remove the decimal point)
S2 : constant String := S1 (S1'First .. Natural'Min (S1'Last, Index_Decimal + Aft));
S3 : constant String := SF.Tail (S2, Natural'Max (S2'Length, Fore + 1 + Aft), ' ');
begin
return S3;
end Format;
type String_Access is not null access String;
Suffices : constant array (1 .. 3) of String_Access
:= (new String'("s"),
new String'("ms"),
new String'("us"));
function Image (Value : Duration) return String is
Number : Duration := Value;
Last_Suffix : constant String_Access := Suffices (Suffices'Last);
Suffix : String_Access := Suffices (Suffices'First);
begin
for S of Suffices loop
Suffix := S;
exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix;
Number := Number * 1e3;
end loop;
begin
return Format (Number, Fore => 5, Aft => 3) & " " & Suffix.all;
exception
when others =>
return Number'Image & " " & Suffix.all;
end;
end Image;
function Trim (Value : String) return String renames Orka.Strings.Trim;
function Strip_Line_Term (Value : String) return String renames Orka.Strings.Strip_Line_Term;
end Orka.Terminals;
|
-- 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 Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with Orka.OS;
with Orka.Strings;
package body Orka.Terminals is
Style_Codes : constant array (Style) of Natural :=
(Default => 0,
Bold => 1,
Dark => 2,
Italic => 3,
Underline => 4,
Blink => 5,
Reversed => 7,
Cross_Out => 9);
type Color_Kind is (FG, BG, None);
type Color_Code is range 0 .. 255;
type Color_Component is range 0 .. 5;
type Color_Index is (R, G, B);
type Color_RGB is array (Color_Index) of Color_Component;
Colors : constant array (Color) of Color_RGB :=
(Default => (0, 0, 0),
Grey => (2, 2, 2),
Red => (4, 0, 0),
Green => (1, 3, 0),
Yellow => (4, 3, 0),
Blue => (0, 1, 4),
Magenta => (4, 0, 3),
Cyan => (0, 4, 3),
White => (4, 4, 4));
package L1 renames Ada.Characters.Latin_1;
package SF renames Ada.Strings.Fixed;
Reset : constant String := L1.ESC & "[0m";
function Sequence (Code : Natural) return String is
Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both);
begin
return (if Code /= 0 then L1.ESC & "[" & Image & "m" else "");
end Sequence;
function Sequence (Kind : Color_Kind; Color : Color_RGB) return String is
Code : constant Color_Code :=
Color_Code (16 + 36 * Color_Code (Color (R)) +
6 * Color_Code (Color (G)) +
Color_Code (Color (B)));
Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both);
begin
return
(case Kind is
when FG => L1.ESC & "[38;5;" & Image & "m",
when BG => L1.ESC & "[48;5;" & Image & "m",
when None => "");
end Sequence;
function Colorize
(Text : String;
Foreground, Background : Color := Default;
Attribute : Style := Default) return String
is
FG_Kind : constant Color_Kind := (if Foreground /= Default then FG else None);
BG_Kind : constant Color_Kind := (if Background /= Default then BG else None);
FG : constant String := Sequence (FG_Kind, Colors (Foreground));
BG : constant String := Sequence (BG_Kind, Colors (Background));
ST : constant String := Sequence (Style_Codes (Attribute));
begin
return Reset & FG & BG & ST & Text & Reset;
end Colorize;
-----------------------------------------------------------------------------
Time_Zero : Duration := 0.0;
procedure Set_Time_Zero (Time : Duration) is
begin
Time_Zero := Time;
end Set_Time_Zero;
Day_In_Seconds : constant := 24.0 * 60.0 * 60.0;
function Time_Image return String is
Seconds_Since_Zero : Duration := Orka.OS.Monotonic_Clock - Time_Zero;
Days_Since_Zero : Natural := 0;
begin
while Seconds_Since_Zero > Day_In_Seconds loop
Seconds_Since_Zero := Seconds_Since_Zero - Day_In_Seconds;
Days_Since_Zero := Days_Since_Zero + 1;
end loop;
declare
Seconds_Rounded : constant Natural :=
Natural (Duration'Max (0.0, Seconds_Since_Zero - 0.5));
Hour : constant Natural := Seconds_Rounded / 3600;
Minute : constant Natural := (Seconds_Rounded mod 3600) / 60;
Second : constant Natural := Seconds_Rounded mod 60;
Sub_Second : constant Duration :=
Seconds_Since_Zero - Duration (Hour * 3600 + Minute * 60 + Second);
-- Remove first character (space) from ' hhmmss' image and then pad it to six digits
Image1 : constant String := Natural'Image
((Days_Since_Zero * 24 + Hour) * 1e4 + Minute * 1e2 + Second);
Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0');
-- Insert ':' characters to get 'hh:mm:ss'
Image3 : constant String := SF.Insert (Image2, 5, ":");
Image4 : constant String := SF.Insert (Image3, 3, ":");
-- Take image without first character (space) and then pad it to six digits
Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6));
Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0');
begin
return Image4 & "." & Image6;
end;
end Time_Image;
function Format (Value : Duration; Fore, Aft : Positive) return String is
package SF renames Ada.Strings.Fixed;
Aft_Shift : constant Positive := 10 ** Aft;
New_Value : constant Duration := Duration (Integer (Value * Aft_Shift)) / Aft_Shift;
S1 : constant String := SF.Trim (New_Value'Image, Ada.Strings.Both);
Index_Decimal : constant Natural := SF.Index (S1, ".");
-- Following code assumes that Aft >= 1 (If Aft = 0 then Aft must
-- be decremented to remove the decimal point)
S2 : constant String := S1 (S1'First .. Natural'Min (S1'Last, Index_Decimal + Aft));
S3 : constant String := SF.Tail (S2, Natural'Max (S2'Length, Fore + 1 + Aft), ' ');
begin
return S3;
end Format;
type String_Access is not null access String;
Suffices : constant array (1 .. 3) of String_Access
:= (new String'("s"),
new String'("ms"),
new String'("us"));
function Image (Value : Duration) return String is
Number : Duration := Value;
Last_Suffix : constant String_Access := Suffices (Suffices'Last);
Suffix : String_Access := Suffices (Suffices'First);
begin
for S of Suffices loop
Suffix := S;
exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix;
Number := Number * 1e3;
end loop;
begin
return Format (Number, Fore => 5, Aft => 3) & " " & Suffix.all;
exception
when others =>
return Number'Image & " " & Suffix.all;
end;
end Image;
function Trim (Value : String) return String renames Orka.Strings.Trim;
function Strip_Line_Term (Value : String) return String renames Orka.Strings.Strip_Line_Term;
end Orka.Terminals;
|
Use 256-color mode when colorizing log messages
|
orka: Use 256-color mode when colorizing log messages
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
9f9eefae509e88df0909bb6a6ae3a0ec89f021d7
|
orka/src/orka/implementation/orka-loggers-formatting.adb
|
orka/src/orka/implementation/orka-loggers-formatting.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2019 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.Terminals;
package body Orka.Loggers.Formatting is
function Format_Message
(From : Source;
Kind : Message_Type;
Level : Severity;
Message : String;
Colorize : Boolean) return String
is
Level_Color : constant Terminals.Color
:= (case Level is
when Error => Terminals.Red,
when Warning => Terminals.Yellow,
when Info => Terminals.Blue,
when Debug => Terminals.Green);
Time_Level : constant String := "[" & Terminals.Time_Image & " " & Level'Image & "]";
From_Kind : constant String := "[" & From'Image & ":" & Kind'Image & "]";
begin
if Colorize then
return
Terminals.Colorize (Time_Level, Level_Color) &
" " &
Terminals.Colorize (From_Kind, Terminals.Magenta) &
" " & Terminals.Strip_Line_Term (Message);
else
return Time_Level & " " & From_Kind & " " & Terminals.Strip_Line_Term (Message);
end if;
end Format_Message;
end Orka.Loggers.Formatting;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2019 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.Strings.Fixed;
with Orka.Terminals;
package body Orka.Loggers.Formatting is
package SF renames Ada.Strings.Fixed;
Length_Level : constant := 5;
Length_Source : constant := 15;
function Format_Message
(From : Source;
Kind : Message_Type;
Level : Severity;
Message : String;
Colorize : Boolean) return String
is
Level_Color : constant Terminals.Color
:= (case Level is
when Error => Terminals.Red,
when Warning => Terminals.Yellow,
when Info => Terminals.Blue,
when Debug => Terminals.Green);
Time_Level : constant String :=
"[" & Terminals.Time_Image & " " & SF.Head (Level'Image, Length_Level) & "]";
Kind_Image : constant String := "[" & SF.Head (From'Image, Length_Source) & "]"
& (if Kind in Other | Error then "" else " [" & Kind'Image & "]");
function Colorize_Text (Text : String; Color : Terminals.Color) return String is
(if Colorize then Terminals.Colorize (Text, Color) else Text);
begin
return
Colorize_Text (Time_Level, Level_Color) &
" " &
Colorize_Text (Kind_Image, Terminals.Magenta) &
" " & Terminals.Strip_Line_Term (Message);
end Format_Message;
end Orka.Loggers.Formatting;
|
Align various parts of log messages
|
orka: Align various parts of log messages
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
4f9efcf2e68d3dc46ce0567ac58ad5d02c87349d
|
awa/plugins/awa-settings/src/awa-settings-modules.adb
|
awa/plugins/awa-settings/src/awa-settings-modules.adb
|
-----------------------------------------------------------------------
-- awa-settings-modules -- Module awa-settings
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Sessions;
with ADO.Queries;
with AWA.Services.Contexts;
with AWA.Settings.Models;
with AWA.Modules.Get;
with AWA.Users.Models;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Beans.Basic;
package body AWA.Settings.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Settings.Module");
package ASC renames AWA.Services.Contexts;
-- Load the setting value for the current user.
-- Return the default value if there is no such setting.
procedure Load (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String);
-- Save the setting value for the current user.
procedure Save (Name : in String;
Value : in String);
-- ------------------------------
-- Set the user setting with the given name in the setting manager cache
-- and in the database.
-- ------------------------------
procedure Set (Manager : in out Setting_Manager;
Name : in String;
Value : in String) is
begin
Manager.Data.Set (Name, Value);
end Set;
-- ------------------------------
-- Get the user setting with the given name from the setting manager cache.
-- Load the user setting from the database if necessary.
-- ------------------------------
procedure Get (Manager : in out Setting_Manager;
Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
begin
Manager.Data.Get (Name, Default, Value);
end Get;
-- ------------------------------
-- Get the current setting manager for the current user.
-- ------------------------------
function Current return Setting_Manager_Access is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Obj : Util.Beans.Objects.Object := Ctx.Get_Session_Attribute (SESSION_ATTR_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Obj);
begin
if Bean = null or else not (Bean.all in Setting_Manager'Class) then
declare
Mgr : constant Setting_Manager_Access := new Setting_Manager;
begin
Obj := Util.Beans.Objects.To_Object (Mgr.all'Access);
Ctx.Set_Session_Attribute (SESSION_ATTR_NAME, Obj);
return Mgr;
end;
else
return Setting_Manager'Class (Bean.all)'Unchecked_Access;
end if;
end Current;
-- ------------------------------
-- Initialize the settings module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Setting_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the settings module");
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the settings module.
-- ------------------------------
function Get_Setting_Module return Setting_Module_Access is
function Get is new AWA.Modules.Get (Setting_Module, Setting_Module_Access, NAME);
begin
return Get;
end Get_Setting_Module;
-- ------------------------------
-- Load the setting value for the current user.
-- Return the default value if there is no such setting.
-- ------------------------------
procedure Load (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.Queries.Context;
Setting : AWA.Settings.Models.User_Setting_Ref;
Found : Boolean;
begin
Query.Set_Join ("INNER JOIN awa_setting AS a ON o.setting_id = a.id ");
Query.Set_Filter ("a.name = :name AND o.user_id = :user");
Query.Bind_Param ("name", Name);
Query.Bind_Param ("user", User.Get_Id);
Setting.Find (DB, Query, Found);
if not Found then
Value := Ada.Strings.Unbounded.To_Unbounded_String (Default);
else
Value := Setting.Get_Value;
end if;
end Load;
-- Save the setting value for the current user.
procedure Save (Name : in String;
Value : in String) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Setting : AWA.Settings.Models.User_Setting_Ref;
Query : ADO.Queries.Context;
Found : Boolean;
begin
Ctx.Start;
Query.Set_Join ("INNER JOIN awa_setting AS a ON o.setting_id = a.id ");
Query.Set_Filter ("a.name = :name AND o.user_id = :user");
Query.Bind_Param ("name", Name);
Query.Bind_Param ("user", User.Get_Id);
Setting.Find (DB, Query, Found);
if not Found then
declare
Setting_Def : AWA.Settings.Models.Setting_Ref;
begin
Query.Clear;
Query.Set_Filter ("o.name = :name");
Query.Bind_Param ("name", Name);
Setting_Def.Find (DB, Query, Found);
if not Found then
Setting_Def.Set_Name (Name);
Setting_Def.Save (DB);
end if;
Setting.Set_Setting (Setting_Def);
end;
Setting.Set_User (User);
end if;
Setting.Set_Value (Value);
Setting.Save (DB);
Ctx.Commit;
end Save;
procedure Free is new Ada.Unchecked_Deallocation (Object => Setting_Data,
Name => Setting_Data_Access);
use Ada.Strings.Unbounded;
protected body Settings is
procedure Get (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
Item : Setting_Data_Access := First;
Previous : Setting_Data_Access := null;
begin
while Item /= null loop
if Item.Name = Name then
Value := Item.Value;
if Previous /= null then
Previous.Next_Setting := Item.Next_Setting;
First := Item;
end if;
return;
end if;
Previous := Item;
Item := Item.Next_Setting;
end loop;
Load (Name, Default, Value);
Item := new Setting_Data;
Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
Item.Value := Value;
Item.Next_Setting := First;
First := Item;
end Get;
procedure Set (Name : in String;
Value : in String) is
Item : Setting_Data_Access := First;
Previous : Setting_Data_Access := null;
begin
while Item /= null loop
if Item.Name = Name then
if Previous /= null then
Previous.Next_Setting := Item.Next_Setting;
First := Item;
end if;
if Item.Value = Value then
return;
end if;
Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value);
Save (Name, Value);
return;
end if;
Previous := Item;
Item := Item.Next_Setting;
end loop;
Item := new Setting_Data;
Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value);
Item.Next_Setting := First;
First := Item;
Save (Name, Value);
end Set;
procedure Clear is
begin
while First /= null loop
declare
Item : Setting_Data_Access := First;
begin
First := Item.Next_Setting;
Free (Item);
end;
end loop;
end Clear;
end Settings;
end AWA.Settings.Modules;
|
-----------------------------------------------------------------------
-- awa-settings-modules -- Module awa-settings
-- Copyright (C) 2013, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Sessions;
with ADO.Queries;
with AWA.Services.Contexts;
with AWA.Settings.Models;
with AWA.Modules.Get;
with AWA.Users.Models;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Beans.Basic;
package body AWA.Settings.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Settings.Module");
package ASC renames AWA.Services.Contexts;
-- Load the setting value for the current user.
-- Return the default value if there is no such setting.
procedure Load (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String);
-- Save the setting value for the current user.
procedure Save (Name : in String;
Value : in String);
-- ------------------------------
-- Set the user setting with the given name in the setting manager cache
-- and in the database.
-- ------------------------------
procedure Set (Manager : in out Setting_Manager;
Name : in String;
Value : in String) is
begin
Manager.Data.Set (Name, Value);
end Set;
-- ------------------------------
-- Get the user setting with the given name from the setting manager cache.
-- Load the user setting from the database if necessary.
-- ------------------------------
procedure Get (Manager : in out Setting_Manager;
Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
begin
Manager.Data.Get (Name, Default, Value);
end Get;
-- ------------------------------
-- Release the memory allocated for the settings.
-- ------------------------------
overriding
procedure Finalize (Manager : in out Setting_Manager) is
begin
Manager.Data.Clear;
end Finalize;
-- ------------------------------
-- Get the current setting manager for the current user.
-- ------------------------------
function Current return Setting_Manager_Access is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Obj : Util.Beans.Objects.Object := Ctx.Get_Session_Attribute (SESSION_ATTR_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Obj);
begin
if Bean = null or else not (Bean.all in Setting_Manager'Class) then
declare
Mgr : constant Setting_Manager_Access := new Setting_Manager;
begin
Obj := Util.Beans.Objects.To_Object (Mgr.all'Access);
Ctx.Set_Session_Attribute (SESSION_ATTR_NAME, Obj);
return Mgr;
end;
else
return Setting_Manager'Class (Bean.all)'Unchecked_Access;
end if;
end Current;
-- ------------------------------
-- Initialize the settings module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Setting_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the settings module");
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the settings module.
-- ------------------------------
function Get_Setting_Module return Setting_Module_Access is
function Get is new AWA.Modules.Get (Setting_Module, Setting_Module_Access, NAME);
begin
return Get;
end Get_Setting_Module;
-- ------------------------------
-- Load the setting value for the current user.
-- Return the default value if there is no such setting.
-- ------------------------------
procedure Load (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.Queries.Context;
Setting : AWA.Settings.Models.User_Setting_Ref;
Found : Boolean;
begin
Query.Set_Join ("INNER JOIN awa_setting AS a ON o.setting_id = a.id ");
Query.Set_Filter ("a.name = :name AND o.user_id = :user");
Query.Bind_Param ("name", Name);
Query.Bind_Param ("user", User.Get_Id);
Setting.Find (DB, Query, Found);
if not Found then
Value := Ada.Strings.Unbounded.To_Unbounded_String (Default);
else
Value := Setting.Get_Value;
end if;
end Load;
-- Save the setting value for the current user.
procedure Save (Name : in String;
Value : in String) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Setting : AWA.Settings.Models.User_Setting_Ref;
Query : ADO.Queries.Context;
Found : Boolean;
begin
Ctx.Start;
Query.Set_Join ("INNER JOIN awa_setting AS a ON o.setting_id = a.id ");
Query.Set_Filter ("a.name = :name AND o.user_id = :user");
Query.Bind_Param ("name", Name);
Query.Bind_Param ("user", User.Get_Id);
Setting.Find (DB, Query, Found);
if not Found then
declare
Setting_Def : AWA.Settings.Models.Setting_Ref;
begin
Query.Clear;
Query.Set_Filter ("o.name = :name");
Query.Bind_Param ("name", Name);
Setting_Def.Find (DB, Query, Found);
if not Found then
Setting_Def.Set_Name (Name);
Setting_Def.Save (DB);
end if;
Setting.Set_Setting (Setting_Def);
end;
Setting.Set_User (User);
end if;
Setting.Set_Value (Value);
Setting.Save (DB);
Ctx.Commit;
end Save;
procedure Free is new Ada.Unchecked_Deallocation (Object => Setting_Data,
Name => Setting_Data_Access);
use Ada.Strings.Unbounded;
protected body Settings is
procedure Get (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
Item : Setting_Data_Access := First;
Previous : Setting_Data_Access := null;
begin
while Item /= null loop
if Item.Name = Name then
Value := Item.Value;
if Previous /= null then
Previous.Next_Setting := Item.Next_Setting;
Item.Next_Setting := First;
First := Item;
end if;
return;
end if;
Previous := Item;
Item := Item.Next_Setting;
end loop;
Load (Name, Default, Value);
Item := new Setting_Data;
Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
Item.Value := Value;
Item.Next_Setting := First;
First := Item;
end Get;
procedure Set (Name : in String;
Value : in String) is
Item : Setting_Data_Access := First;
Previous : Setting_Data_Access := null;
begin
while Item /= null loop
if Item.Name = Name then
if Previous /= null then
Previous.Next_Setting := Item.Next_Setting;
Item.Next_Setting := First;
First := Item;
end if;
if Item.Value = Value then
return;
end if;
Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value);
Save (Name, Value);
return;
end if;
Previous := Item;
Item := Item.Next_Setting;
end loop;
Item := new Setting_Data;
Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value);
Item.Next_Setting := First;
First := Item;
Save (Name, Value);
end Set;
procedure Clear is
begin
while First /= null loop
declare
Item : Setting_Data_Access := First;
begin
First := Item.Next_Setting;
Free (Item);
end;
end loop;
end Clear;
end Settings;
end AWA.Settings.Modules;
|
Implement the Finalize procedure to release the settings Fix Get and Set protected operations to move the setting at head of the list
|
Implement the Finalize procedure to release the settings
Fix Get and Set protected operations to move the setting at head of the list
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
671aa0d9104050d9ea95adcd7f825f65573dca39
|
src/gl/interface/gl-objects-textures.ads
|
src/gl/interface/gl-objects-textures.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 System;
with Interfaces.C.Pointers;
with Ada.Unchecked_Deallocation;
with GL.Low_Level.Enums;
with GL.Objects.Buffers;
with GL.Pixels.Extensions;
with GL.Types.Colors;
package GL.Objects.Textures is
pragma Preelaborate;
package LE renames Low_Level.Enums;
package PE renames Pixels.Extensions;
use all type LE.Texture_Kind;
type Dimension_Count is (One, Two, Three);
function Get_Dimensions (Kind : LE.Texture_Kind) return Dimension_Count;
function Maximum_Anisotropy return Single
with Post => Maximum_Anisotropy'Result >= 16.0;
-----------------------------------------------------------------------------
-- Basic Types --
-----------------------------------------------------------------------------
type Minifying_Function is (Nearest, Linear, Nearest_Mipmap_Nearest,
Linear_Mipmap_Nearest, Nearest_Mipmap_Linear,
Linear_Mipmap_Linear);
-- Has to be defined here because of following subtype declaration.
for Minifying_Function use (Nearest => 16#2600#,
Linear => 16#2601#,
Nearest_Mipmap_Nearest => 16#2700#,
Linear_Mipmap_Nearest => 16#2701#,
Nearest_Mipmap_Linear => 16#2702#,
Linear_Mipmap_Linear => 16#2703#);
for Minifying_Function'Size use Int'Size;
subtype Magnifying_Function is Minifying_Function range Nearest .. Linear;
type Wrapping_Mode is (Repeat, Clamp_To_Border, Clamp_To_Edge,
Mirrored_Repeat, Mirror_Clamp_To_Edge);
-- Actual range is implementation-defined
--
-- - OpenGL 2.x: At least 2
-- - OpenGL 3.x: At least 48
-- - OpenGL 4.x: At least 80
subtype Texture_Unit is UInt;
subtype Image_Unit is UInt;
subtype Mipmap_Level is Size;
-----------------------------------------------------------------------------
-- Texture Objects --
-----------------------------------------------------------------------------
type Texture_Base (Kind : LE.Texture_Kind)
is abstract new GL_Object with private;
function Has_Levels (Object : Texture_Base) return Boolean is
(Object.Kind not in Texture_Buffer | Texture_Rectangle |
Texture_2D_Multisample | Texture_2D_Multisample_Array)
with Inline;
overriding
procedure Initialize_Id (Object : in out Texture_Base);
overriding
procedure Delete_Id (Object : in out Texture_Base);
overriding
function Identifier (Object : Texture_Base) return Types.Debug.Identifier is
(Types.Debug.Texture);
procedure Invalidate_Image (Object : Texture_Base; Level : Mipmap_Level)
with Pre => (if not Object.Has_Levels then Level = 0);
procedure Invalidate_Sub_Image (Object : Texture_Base; Level : Mipmap_Level;
X, Y, Z : Int; Width, Height, Depth : Size)
with Pre => (if not Object.Has_Levels then Level = 0);
procedure Bind_Texture_Unit (Object : Texture_Base; Unit : Texture_Unit);
procedure Bind_Image_Texture (Object : Texture_Base; Unit : Image_Unit);
-----------------------------------------------------------------------------
type Texture is new Texture_Base with private;
function Dimensions (Object : Texture) return Dimension_Count;
function Allocated (Object : Texture) return Boolean;
procedure Clear_Using_Data
(Object : Texture; Level : Mipmap_Level;
Source_Format : Pixels.Format;
Source_Type : Pixels.Data_Type;
Source : System.Address)
with Pre => not Object.Compressed (Level);
procedure Clear_Using_Zeros
(Object : Texture; Level : Mipmap_Level)
with Pre => not Object.Compressed (Level);
procedure Generate_Mipmap (Object : Texture);
-----------------------------------------------------------------------------
-- Texture Parameters --
-----------------------------------------------------------------------------
procedure Set_Minifying_Filter (Object : Texture; Filter : Minifying_Function);
procedure Set_Magnifying_Filter (Object : Texture; Filter : Magnifying_Function);
procedure Set_Minimum_LoD (Object : Texture; Level : Double);
procedure Set_Maximum_LoD (Object : Texture; Level : Double);
procedure Set_Lowest_Mipmap_Level (Object : Texture; Level : Mipmap_Level);
procedure Set_Highest_Mipmap_Level (Object : Texture; Level : Mipmap_Level);
procedure Set_Seamless_Filtering (Object : Texture; Enable : Boolean)
with Pre => Object.Kind in Texture_Cube_Map | Texture_Cube_Map_Array;
-- Enable seamless cubemap filtering
--
-- Note: this procedure requires the ARB_seamless_cubemap_per_texture
-- extension. If this extension is not available, you can enable seamless
-- filtering globally via GL.Toggles.
function Minifying_Filter (Object : Texture) return Minifying_Function;
function Magnifying_Filter (Object : Texture) return Magnifying_Function;
function Minimum_LoD (Object : Texture) return Double;
function Maximum_LoD (Object : Texture) return Double;
function Lowest_Mipmap_Level (Object : Texture) return Mipmap_Level;
function Highest_Mipmap_Level (Object : Texture) return Mipmap_Level;
-- TODO LoD_Bias (Double)
function Seamless_Filtering (Object : Texture) return Boolean
with Pre => Object.Kind in Texture_Cube_Map | Texture_Cube_Map_Array;
procedure Set_Max_Anisotropy (Object : Texture; Degree : Double)
with Pre => Degree >= 1.0;
-- Set the maximum amount of anisotropy filtering to reduce the blurring
-- of textures (caused by mipmap filtering) that are viewed at an
-- oblique angle.
--
-- For best results, combine the use of anisotropy filtering with
-- a Linear_Mipmap_Linear minification filter and a Linear maxification
-- filter.
function Max_Anisotropy (Object : Texture) return Double
with Post => Max_Anisotropy'Result >= 1.0;
procedure Set_X_Wrapping (Object : Texture; Mode : Wrapping_Mode);
procedure Set_Y_Wrapping (Object : Texture; Mode : Wrapping_Mode);
procedure Set_Z_Wrapping (Object : Texture; Mode : Wrapping_Mode);
function X_Wrapping (Object : Texture) return Wrapping_Mode;
function Y_Wrapping (Object : Texture) return Wrapping_Mode;
function Z_Wrapping (Object : Texture) return Wrapping_Mode;
procedure Set_Border_Color (Object : Texture; Color : Colors.Color);
function Border_Color (Object : Texture) return Colors.Color;
procedure Toggle_Compare_X_To_Texture (Object : Texture; Enabled : Boolean);
procedure Set_Compare_Function (Object : Texture; Func : Compare_Function);
function Compare_X_To_Texture_Enabled (Object : Texture) return Boolean;
function Current_Compare_Function (Object : Texture) return Compare_Function;
-----------------------------------------------------------------------------
-- Texture Level Parameters --
-----------------------------------------------------------------------------
function Width (Object : Texture; Level : Mipmap_Level) return Size;
function Height (Object : Texture; Level : Mipmap_Level) return Size;
function Depth (Object : Texture; Level : Mipmap_Level) return Size;
function Internal_Format (Object : Texture; Level : Mipmap_Level)
return Pixels.Internal_Format
with Pre => Object.Allocated and not Object.Compressed (Level);
function Compressed_Format (Object : Texture; Level : Mipmap_Level)
return Pixels.Compressed_Format
with Pre => Object.Allocated and Object.Compressed (Level);
function Red_Type (Object : Texture; Level : Mipmap_Level)
return Pixels.Channel_Data_Type;
function Green_Type (Object : Texture; Level : Mipmap_Level)
return Pixels.Channel_Data_Type;
function Blue_Type (Object : Texture; Level : Mipmap_Level)
return Pixels.Channel_Data_Type;
function Alpha_Type (Object : Texture; Level : Mipmap_Level)
return Pixels.Channel_Data_Type;
function Depth_Type (Object : Texture; Level : Mipmap_Level)
return Pixels.Channel_Data_Type;
function Red_Size (Object : Texture; Level : Mipmap_Level) return Size;
function Green_Size (Object : Texture; Level : Mipmap_Level) return Size;
function Blue_Size (Object : Texture; Level : Mipmap_Level) return Size;
function Alpha_Size (Object : Texture; Level : Mipmap_Level) return Size;
function Depth_Size (Object : Texture; Level : Mipmap_Level) return Size;
-- TODO Stencil_Size, Shared_Size
function Compressed (Object : Texture; Level : Mipmap_Level) return Boolean;
function Compressed_Image_Size (Object : Texture; Level : Mipmap_Level) return Size;
-- TODO Pre => Object is compressed
-- TODO Samples (Size), Fixed_Sample_Locations (Boolean) (if Object is multisampled)
function Buffer_Offset (Object : Texture; Level : Mipmap_Level) return Size;
function Buffer_Size (Object : Texture; Level : Mipmap_Level) return Size;
-----------------------------------------------------------------------------
-- Texture Units --
-----------------------------------------------------------------------------
function Active_Unit return Texture_Unit;
function Texture_Unit_Count return Natural;
-----------------------------------------------------------------------------
-- Buffer Texture Loading --
-----------------------------------------------------------------------------
type Buffer_Texture is new Texture_Base (Kind => Texture_Buffer) with private;
procedure Attach_Buffer (Object : Buffer_Texture;
Internal_Format : Pixels.Internal_Format_Buffer_Texture;
Buffer : Objects.Buffers.Buffer);
procedure Attach_Buffer (Object : Buffer_Texture;
Internal_Format : Pixels.Internal_Format_Buffer_Texture;
Buffer : Objects.Buffers.Buffer;
Offset, Size : Types.Size);
-----------------------------------------------------------------------------
-- Texture Loading --
-----------------------------------------------------------------------------
procedure Allocate_Storage
(Object : in out Texture;
Levels, Samples : Types.Size;
Format : Pixels.Internal_Format;
Width, Height, Depth : Types.Size;
Fixed_Locations : Boolean := True)
with Pre => not Object.Allocated,
Post => Object.Allocated;
procedure Allocate_Storage
(Object : in out Texture;
Levels, Samples : Types.Size;
Format : Pixels.Compressed_Format;
Width, Height, Depth : Types.Size;
Fixed_Locations : Boolean := True)
with Pre => not Object.Allocated and Object.Kind /= Texture_Rectangle,
Post => Object.Allocated;
procedure Load_From_Data
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size;
Source_Format : Pixels.Format;
Source_Type : Pixels.Data_Type;
Source : System.Address)
with Pre => Object.Allocated and not Object.Compressed (Level);
procedure Load_From_Data
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size;
Source_Format : Pixels.Compressed_Format;
Image_Size : Types.Size;
Source : System.Address)
with Pre => Object.Dimensions /= One and Object.Allocated and Object.Compressed (Level);
procedure Copy_Data
(Object : Texture;
Subject : Texture;
Source_Level, Target_Level : Mipmap_Level)
with Pre => Object.Allocated and Subject.Allocated;
procedure Copy_Sub_Data
(Object : Texture;
Subject : Texture;
Source_Level, Target_Level : Mipmap_Level;
Source_X, Source_Y, Source_Z : Types.Size := 0;
Target_X, Target_Y, Target_Z : Types.Size := 0;
Width, Height, Depth : Types.Size)
with Pre => Object.Allocated and Subject.Allocated;
procedure Clear_Using_Data
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size;
Source_Format : Pixels.Format;
Source_Type : Pixels.Data_Type;
Source : System.Address)
with Pre => not Object.Compressed (Level);
procedure Clear_Using_Zeros
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size)
with Pre => not Object.Compressed (Level);
-----------------------------------------------------------------------------
function Get_Compressed_Data
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size;
Format : Pixels.Compressed_Format) return not null Types.UByte_Array_Access
with Pre => Object.Dimensions /= One and Object.Allocated and Object.Compressed (Level)
and Object.Kind not in Texture_2D_Multisample | Texture_2D_Multisample_Array;
generic
with package Pointers is new Interfaces.C.Pointers (<>);
package Texture_Pointers is
type Element_Array_Access is access Pointers.Element_Array;
procedure Free is new Ada.Unchecked_Deallocation
(Object => Pointers.Element_Array, Name => Element_Array_Access);
function Get_Data
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size;
Format : Pixels.Format;
Data_Type : PE.Non_Packed_Data_Type) return not null Element_Array_Access
with Pre => Object.Allocated and
not Object.Compressed (Level) and PE.Compatible (Format, Data_Type);
end Texture_Pointers;
private
for Wrapping_Mode use
(Repeat => 16#2901#,
Clamp_To_Border => 16#812D#,
Clamp_To_Edge => 16#812F#,
Mirrored_Repeat => 16#8370#,
Mirror_Clamp_To_Edge => 16#8743#);
for Wrapping_Mode'Size use Int'Size;
type Texture_Base (Kind : LE.Texture_Kind)
is new GL_Object with null record;
type Texture is new Texture_Base with record
Allocated : Boolean := False;
Dimensions : Dimension_Count := Get_Dimensions (Texture.Kind);
end record;
type Buffer_Texture is new Texture_Base (Kind => Texture_Buffer) with null record;
end GL.Objects.Textures;
|
-- 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 System;
with Interfaces.C.Pointers;
with Ada.Unchecked_Deallocation;
with GL.Low_Level.Enums;
with GL.Objects.Buffers;
with GL.Pixels.Extensions;
with GL.Types.Colors;
package GL.Objects.Textures is
pragma Preelaborate;
package LE renames Low_Level.Enums;
package PE renames Pixels.Extensions;
use all type LE.Texture_Kind;
type Dimension_Count is (One, Two, Three);
function Get_Dimensions (Kind : LE.Texture_Kind) return Dimension_Count;
function Maximum_Anisotropy return Single
with Post => Maximum_Anisotropy'Result >= 16.0;
-----------------------------------------------------------------------------
-- Basic Types --
-----------------------------------------------------------------------------
type Minifying_Function is (Nearest, Linear, Nearest_Mipmap_Nearest,
Linear_Mipmap_Nearest, Nearest_Mipmap_Linear,
Linear_Mipmap_Linear);
-- Has to be defined here because of following subtype declaration.
for Minifying_Function use (Nearest => 16#2600#,
Linear => 16#2601#,
Nearest_Mipmap_Nearest => 16#2700#,
Linear_Mipmap_Nearest => 16#2701#,
Nearest_Mipmap_Linear => 16#2702#,
Linear_Mipmap_Linear => 16#2703#);
for Minifying_Function'Size use Int'Size;
subtype Magnifying_Function is Minifying_Function range Nearest .. Linear;
type Wrapping_Mode is (Repeat, Clamp_To_Border, Clamp_To_Edge,
Mirrored_Repeat, Mirror_Clamp_To_Edge);
-- Actual range is implementation-defined
--
-- - OpenGL 2.x: At least 2
-- - OpenGL 3.x: At least 48
-- - OpenGL 4.x: At least 80
subtype Texture_Unit is UInt;
subtype Image_Unit is UInt;
subtype Mipmap_Level is Size;
-----------------------------------------------------------------------------
-- Texture Objects --
-----------------------------------------------------------------------------
type Texture_Base (Kind : LE.Texture_Kind)
is abstract new GL_Object with private;
function Has_Levels (Object : Texture_Base) return Boolean is
(Object.Kind not in Texture_Buffer | Texture_Rectangle |
Texture_2D_Multisample | Texture_2D_Multisample_Array)
with Inline;
overriding
procedure Initialize_Id (Object : in out Texture_Base);
overriding
procedure Delete_Id (Object : in out Texture_Base);
overriding
function Identifier (Object : Texture_Base) return Types.Debug.Identifier is
(Types.Debug.Texture);
procedure Invalidate_Image (Object : Texture_Base; Level : Mipmap_Level)
with Pre => (if not Object.Has_Levels then Level = 0);
procedure Invalidate_Sub_Image (Object : Texture_Base; Level : Mipmap_Level;
X, Y, Z : Int; Width, Height, Depth : Size)
with Pre => (if not Object.Has_Levels then Level = 0);
procedure Bind_Texture_Unit (Object : Texture_Base; Unit : Texture_Unit);
procedure Bind_Image_Texture (Object : Texture_Base; Unit : Image_Unit);
-----------------------------------------------------------------------------
type Texture is new Texture_Base with private;
function Dimensions (Object : Texture) return Dimension_Count;
function Allocated (Object : Texture) return Boolean;
procedure Clear_Using_Data
(Object : Texture; Level : Mipmap_Level;
Source_Format : Pixels.Format;
Source_Type : Pixels.Data_Type;
Source : System.Address)
with Pre => not Object.Compressed (Level);
procedure Clear_Using_Zeros
(Object : Texture; Level : Mipmap_Level)
with Pre => not Object.Compressed (Level);
procedure Generate_Mipmap (Object : Texture)
with Pre => Object.Has_Levels;
-----------------------------------------------------------------------------
-- Texture Parameters --
-----------------------------------------------------------------------------
procedure Set_Minifying_Filter (Object : Texture; Filter : Minifying_Function)
with Pre => (if Object.Kind = Texture_Rectangle then Filter in Nearest | Linear);
procedure Set_Magnifying_Filter (Object : Texture; Filter : Magnifying_Function);
procedure Set_Minimum_LoD (Object : Texture; Level : Double);
procedure Set_Maximum_LoD (Object : Texture; Level : Double);
procedure Set_Lowest_Mipmap_Level (Object : Texture; Level : Mipmap_Level);
procedure Set_Highest_Mipmap_Level (Object : Texture; Level : Mipmap_Level);
procedure Set_Seamless_Filtering (Object : Texture; Enable : Boolean)
with Pre => Object.Kind in Texture_Cube_Map | Texture_Cube_Map_Array;
-- Enable seamless cubemap filtering
--
-- Note: this procedure requires the ARB_seamless_cubemap_per_texture
-- extension. If this extension is not available, you can enable seamless
-- filtering globally via GL.Toggles.
function Minifying_Filter (Object : Texture) return Minifying_Function;
function Magnifying_Filter (Object : Texture) return Magnifying_Function;
function Minimum_LoD (Object : Texture) return Double;
function Maximum_LoD (Object : Texture) return Double;
function Lowest_Mipmap_Level (Object : Texture) return Mipmap_Level;
function Highest_Mipmap_Level (Object : Texture) return Mipmap_Level;
-- TODO LoD_Bias (Double)
function Seamless_Filtering (Object : Texture) return Boolean
with Pre => Object.Kind in Texture_Cube_Map | Texture_Cube_Map_Array;
procedure Set_Max_Anisotropy (Object : Texture; Degree : Double)
with Pre => Degree >= 1.0;
-- Set the maximum amount of anisotropy filtering to reduce the blurring
-- of textures (caused by mipmap filtering) that are viewed at an
-- oblique angle.
--
-- For best results, combine the use of anisotropy filtering with
-- a Linear_Mipmap_Linear minification filter and a Linear maxification
-- filter.
function Max_Anisotropy (Object : Texture) return Double
with Post => Max_Anisotropy'Result >= 1.0;
procedure Set_X_Wrapping (Object : Texture; Mode : Wrapping_Mode);
procedure Set_Y_Wrapping (Object : Texture; Mode : Wrapping_Mode);
procedure Set_Z_Wrapping (Object : Texture; Mode : Wrapping_Mode);
function X_Wrapping (Object : Texture) return Wrapping_Mode;
function Y_Wrapping (Object : Texture) return Wrapping_Mode;
function Z_Wrapping (Object : Texture) return Wrapping_Mode;
procedure Set_Border_Color (Object : Texture; Color : Colors.Color);
function Border_Color (Object : Texture) return Colors.Color;
procedure Toggle_Compare_X_To_Texture (Object : Texture; Enabled : Boolean);
procedure Set_Compare_Function (Object : Texture; Func : Compare_Function);
function Compare_X_To_Texture_Enabled (Object : Texture) return Boolean;
function Current_Compare_Function (Object : Texture) return Compare_Function;
-----------------------------------------------------------------------------
-- Texture Level Parameters --
-----------------------------------------------------------------------------
function Width (Object : Texture; Level : Mipmap_Level) return Size;
function Height (Object : Texture; Level : Mipmap_Level) return Size;
function Depth (Object : Texture; Level : Mipmap_Level) return Size;
function Internal_Format (Object : Texture; Level : Mipmap_Level)
return Pixels.Internal_Format
with Pre => Object.Allocated and not Object.Compressed (Level);
function Compressed_Format (Object : Texture; Level : Mipmap_Level)
return Pixels.Compressed_Format
with Pre => Object.Allocated and Object.Compressed (Level);
function Red_Type (Object : Texture; Level : Mipmap_Level)
return Pixels.Channel_Data_Type;
function Green_Type (Object : Texture; Level : Mipmap_Level)
return Pixels.Channel_Data_Type;
function Blue_Type (Object : Texture; Level : Mipmap_Level)
return Pixels.Channel_Data_Type;
function Alpha_Type (Object : Texture; Level : Mipmap_Level)
return Pixels.Channel_Data_Type;
function Depth_Type (Object : Texture; Level : Mipmap_Level)
return Pixels.Channel_Data_Type;
function Red_Size (Object : Texture; Level : Mipmap_Level) return Size;
function Green_Size (Object : Texture; Level : Mipmap_Level) return Size;
function Blue_Size (Object : Texture; Level : Mipmap_Level) return Size;
function Alpha_Size (Object : Texture; Level : Mipmap_Level) return Size;
function Depth_Size (Object : Texture; Level : Mipmap_Level) return Size;
-- TODO Stencil_Size, Shared_Size
function Compressed (Object : Texture; Level : Mipmap_Level) return Boolean;
function Compressed_Image_Size (Object : Texture; Level : Mipmap_Level) return Size;
-- TODO Pre => Object is compressed
-- TODO Samples (Size), Fixed_Sample_Locations (Boolean) (if Object is multisampled)
function Buffer_Offset (Object : Texture; Level : Mipmap_Level) return Size;
function Buffer_Size (Object : Texture; Level : Mipmap_Level) return Size;
-----------------------------------------------------------------------------
-- Texture Units --
-----------------------------------------------------------------------------
function Active_Unit return Texture_Unit;
function Texture_Unit_Count return Natural;
-----------------------------------------------------------------------------
-- Buffer Texture Loading --
-----------------------------------------------------------------------------
type Buffer_Texture is new Texture_Base (Kind => Texture_Buffer) with private;
procedure Attach_Buffer (Object : Buffer_Texture;
Internal_Format : Pixels.Internal_Format_Buffer_Texture;
Buffer : Objects.Buffers.Buffer);
procedure Attach_Buffer (Object : Buffer_Texture;
Internal_Format : Pixels.Internal_Format_Buffer_Texture;
Buffer : Objects.Buffers.Buffer;
Offset, Size : Types.Size);
-----------------------------------------------------------------------------
-- Texture Loading --
-----------------------------------------------------------------------------
procedure Allocate_Storage
(Object : in out Texture;
Levels, Samples : Types.Size;
Format : Pixels.Internal_Format;
Width, Height, Depth : Types.Size;
Fixed_Locations : Boolean := True)
with Pre => not Object.Allocated,
Post => Object.Allocated;
procedure Allocate_Storage
(Object : in out Texture;
Levels, Samples : Types.Size;
Format : Pixels.Compressed_Format;
Width, Height, Depth : Types.Size;
Fixed_Locations : Boolean := True)
with Pre => not Object.Allocated and Object.Kind /= Texture_Rectangle,
Post => Object.Allocated;
procedure Load_From_Data
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size;
Source_Format : Pixels.Format;
Source_Type : Pixels.Data_Type;
Source : System.Address)
with Pre => Object.Allocated and not Object.Compressed (Level);
procedure Load_From_Data
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size;
Source_Format : Pixels.Compressed_Format;
Image_Size : Types.Size;
Source : System.Address)
with Pre => Object.Dimensions /= One and Object.Allocated and Object.Compressed (Level);
procedure Copy_Data
(Object : Texture;
Subject : Texture;
Source_Level, Target_Level : Mipmap_Level)
with Pre => Object.Allocated and Subject.Allocated;
procedure Copy_Sub_Data
(Object : Texture;
Subject : Texture;
Source_Level, Target_Level : Mipmap_Level;
Source_X, Source_Y, Source_Z : Types.Size := 0;
Target_X, Target_Y, Target_Z : Types.Size := 0;
Width, Height, Depth : Types.Size)
with Pre => Object.Allocated and Subject.Allocated;
procedure Clear_Using_Data
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size;
Source_Format : Pixels.Format;
Source_Type : Pixels.Data_Type;
Source : System.Address)
with Pre => not Object.Compressed (Level);
procedure Clear_Using_Zeros
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size)
with Pre => not Object.Compressed (Level);
-----------------------------------------------------------------------------
function Get_Compressed_Data
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size;
Format : Pixels.Compressed_Format) return not null Types.UByte_Array_Access
with Pre => Object.Dimensions /= One and Object.Allocated and Object.Compressed (Level)
and Object.Kind not in Texture_2D_Multisample | Texture_2D_Multisample_Array;
generic
with package Pointers is new Interfaces.C.Pointers (<>);
package Texture_Pointers is
type Element_Array_Access is access Pointers.Element_Array;
procedure Free is new Ada.Unchecked_Deallocation
(Object => Pointers.Element_Array, Name => Element_Array_Access);
function Get_Data
(Object : Texture;
Level : Mipmap_Level;
X, Y, Z : Types.Size := 0;
Width, Height, Depth : Types.Positive_Size;
Format : Pixels.Format;
Data_Type : PE.Non_Packed_Data_Type) return not null Element_Array_Access
with Pre => Object.Allocated and
not Object.Compressed (Level) and PE.Compatible (Format, Data_Type);
end Texture_Pointers;
private
for Wrapping_Mode use
(Repeat => 16#2901#,
Clamp_To_Border => 16#812D#,
Clamp_To_Edge => 16#812F#,
Mirrored_Repeat => 16#8370#,
Mirror_Clamp_To_Edge => 16#8743#);
for Wrapping_Mode'Size use Int'Size;
type Texture_Base (Kind : LE.Texture_Kind)
is new GL_Object with null record;
type Texture is new Texture_Base with record
Allocated : Boolean := False;
Dimensions : Dimension_Count := Get_Dimensions (Texture.Kind);
end record;
type Buffer_Texture is new Texture_Base (Kind => Texture_Buffer) with null record;
end GL.Objects.Textures;
|
Add some pre conditions to Generate_Mipmap and Set_Minifying_Filter
|
gl: Add some pre conditions to Generate_Mipmap and Set_Minifying_Filter
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
8f4e015d425047f9dced10357476fd3f8793d566
|
awa/plugins/awa-storages/src/awa-storages-services.adb
|
awa/plugins/awa-storages/src/awa-storages-services.adb
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Log.Loggers;
with ADO.Objects;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Permissions;
with AWA.Storages.Stores.Files;
package body AWA.Storages.Services is
use AWA.Services;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Services");
-- ------------------------------
-- Get the persistent store that manages the data 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 is
begin
return Service.Stores (Kind);
end Get_Store;
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class) is
Root : constant String := Module.Get_Config (Stores.Files.Root_Directory_Parameter.P);
Tmp : constant String := Module.Get_Config (Stores.Files.Tmp_Directory_Parameter.P);
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Stores (Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access;
Service.Stores (Storages.Models.FILE) := AWA.Storages.Stores.Files.Create_File_Store (Root);
Service.Stores (Storages.Models.TMP) := AWA.Storages.Stores.Files.Create_File_Store (Tmp);
Service.Database_Store.Tmp := Service.Stores (Storages.Models.TMP);
end Initialize;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
begin
if not Folder.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Folder.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Folder.Set_Workspace (Workspace);
end if;
-- Check that the user has the create folder permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Folder.Permission,
Entity => Workspace.Get_Id);
Ctx.Start;
if not Folder.Is_Inserted then
Folder.Set_Create_Date (Ada.Calendar.Clock);
Folder.Set_Owner (Ctx.Get_User);
end if;
Folder.Save (DB);
Ctx.Commit;
end Save_Folder;
-- ------------------------------
-- 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) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Folder.Load (Session => DB, Id => Id);
end Load_Folder;
-- ------------------------------
-- 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) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
begin
Storage.Load (Session => DB, Id => Id);
end Load_Storage;
-- ------------------------------
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type) is
begin
Storage_Service'Class (Service).Save (Into, Data.Get_Local_Filename, Storage);
end Save;
-- ------------------------------
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type) is
use type AWA.Storages.Models.Storage_Type;
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
Store : Stores.Store_Access;
Created : Boolean;
begin
Log.Info ("Save {0} in storage space", Path);
Into.Set_Storage (Storage);
Store := Storage_Service'Class (Service).Get_Store (Into.Get_Storage);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage));
end if;
if not Into.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Into.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Into.Set_Workspace (Workspace);
end if;
-- Check that the user has the create storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Storage.Permission,
Entity => Workspace.Get_Id);
Ctx.Start;
Created := not Into.Is_Inserted;
if Created then
Into.Set_Create_Date (Ada.Calendar.Clock);
Into.Set_Owner (Ctx.Get_User);
end if;
Into.Save (DB);
Store.Save (DB, Into, Path);
Into.Save (DB);
-- Notify the listeners.
if Created then
Storage_Lifecycle.Notify_Create (Service, Into);
else
Storage_Lifecycle.Notify_Update (Service, Into);
end if;
Ctx.Commit;
end Save;
-- ------------------------------
-- 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) is
use type AWA.Storages.Models.Storage_Type;
use type AWA.Storages.Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (Models.Query_Storage_Get_Data);
Kind : AWA.Storages.Models.Storage_Type;
begin
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Name := Query.Get_Unbounded_String (2);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (4));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (5);
else
declare
Store : Stores.Store_Access;
Storage : AWA.Storages.Models.Storage_Ref;
File : AWA.Storages.Storage_File;
Found : Boolean;
begin
Store := Storage_Service'Class (Service).Get_Store (Kind);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Kind));
end if;
Storage.Load (DB, From, Found);
if not Found then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Store.Load (DB, Storage, File);
Into := ADO.Create_Blob (AWA.Storages.Get_Path (File));
end;
end if;
end Load;
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File) is
use type Stores.Store_Access;
use type Models.Storage_Type;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.Queries.Context;
Found : Boolean;
Storage : AWA.Storages.Models.Storage_Ref;
Local : AWA.Storages.Models.Store_Local_Ref;
Store : Stores.Store_Access;
begin
if Mode = READ then
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Local);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Local.Find (DB, Query, Found);
if Found then
Into.Path := Local.Get_Path;
return;
end if;
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Storage);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Storage.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
Ctx.Start;
Store := Storage_Service'Class (Service).Get_Store (Storage.Get_Storage);
Store.Load (Session => DB,
From => Storage,
Into => Into);
Ctx.Commit;
end Get_Local_File;
procedure Create_Local_File (Service : in Storage_Service;
Into : out Storage_File) is
begin
null;
end Create_Local_File;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class) is
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Id : constant ADO.Identifier := ADO.Objects.Get_Value (Storage.Get_Key);
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Id));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Id);
Ctx.Start;
Storage_Lifecycle.Notify_Delete (Service, Storage);
Storage.Delete (DB);
Ctx.Commit;
end Delete;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier) is
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
S : AWA.Storages.Models.Storage_Ref;
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (AWA.Storages.Models.Query_Storage_Delete_Local);
Store : Stores.Store_Access;
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Storage));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Storage);
Ctx.Start;
S.Load (Id => Storage, Session => DB);
Store := Storage_Service'Class (Service).Get_Store (S.Get_Storage);
if Store = null then
Log.Error ("There is no store associated with storage item {0}",
ADO.Identifier'Image (Storage));
else
Store.Delete (DB, S);
end if;
Storage_Lifecycle.Notify_Delete (Service, S);
-- Delete the storage instance and all storage that refer to it.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Storages.Models.STORAGE_TABLE);
begin
Stmt.Set_Filter (Filter => "id = ? OR original_id = ?");
Stmt.Add_Param (Value => Storage);
Stmt.Add_Param (Value => Storage);
Stmt.Execute;
end;
-- Delete the local storage instances.
Query.Bind_Param ("store_id", Storage);
Query.Execute;
S.Delete (DB);
Ctx.Commit;
end Delete;
end AWA.Storages.Services;
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Log.Loggers;
with ADO.Objects;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Permissions;
with AWA.Storages.Stores.Files;
package body AWA.Storages.Services is
use AWA.Services;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Services");
-- ------------------------------
-- Get the persistent store that manages the data 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 is
begin
return Service.Stores (Kind);
end Get_Store;
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class) is
Root : constant String := Module.Get_Config (Stores.Files.Root_Directory_Parameter.P);
Tmp : constant String := Module.Get_Config (Stores.Files.Tmp_Directory_Parameter.P);
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Stores (Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access;
Service.Stores (Storages.Models.FILE) := AWA.Storages.Stores.Files.Create_File_Store (Root);
Service.Stores (Storages.Models.TMP) := AWA.Storages.Stores.Files.Create_File_Store (Tmp);
Service.Database_Store.Tmp := Service.Stores (Storages.Models.TMP);
end Initialize;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
begin
if not Folder.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Folder.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Folder.Set_Workspace (Workspace);
end if;
-- Check that the user has the create folder permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Folder.Permission,
Entity => Workspace);
Ctx.Start;
if not Folder.Is_Inserted then
Folder.Set_Create_Date (Ada.Calendar.Clock);
Folder.Set_Owner (Ctx.Get_User);
end if;
Folder.Save (DB);
Ctx.Commit;
end Save_Folder;
-- ------------------------------
-- 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) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Folder.Load (Session => DB, Id => Id);
end Load_Folder;
-- ------------------------------
-- 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) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
begin
Storage.Load (Session => DB, Id => Id);
end Load_Storage;
-- ------------------------------
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type) is
begin
Storage_Service'Class (Service).Save (Into, Data.Get_Local_Filename, Storage);
end Save;
-- ------------------------------
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type) is
use type AWA.Storages.Models.Storage_Type;
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
Store : Stores.Store_Access;
Created : Boolean;
begin
Log.Info ("Save {0} in storage space", Path);
Into.Set_Storage (Storage);
Store := Storage_Service'Class (Service).Get_Store (Into.Get_Storage);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage));
end if;
if not Into.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Into.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Into.Set_Workspace (Workspace);
end if;
-- Check that the user has the create storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Storage.Permission,
Entity => Workspace);
Ctx.Start;
Created := not Into.Is_Inserted;
if Created then
Into.Set_Create_Date (Ada.Calendar.Clock);
Into.Set_Owner (Ctx.Get_User);
end if;
Into.Save (DB);
Store.Save (DB, Into, Path);
Into.Save (DB);
-- Notify the listeners.
if Created then
Storage_Lifecycle.Notify_Create (Service, Into);
else
Storage_Lifecycle.Notify_Update (Service, Into);
end if;
Ctx.Commit;
end Save;
-- ------------------------------
-- 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) is
use type AWA.Storages.Models.Storage_Type;
use type AWA.Storages.Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (Models.Query_Storage_Get_Data);
Kind : AWA.Storages.Models.Storage_Type;
begin
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Name := Query.Get_Unbounded_String (2);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (4));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (5);
else
declare
Store : Stores.Store_Access;
Storage : AWA.Storages.Models.Storage_Ref;
File : AWA.Storages.Storage_File;
Found : Boolean;
begin
Store := Storage_Service'Class (Service).Get_Store (Kind);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Kind));
end if;
Storage.Load (DB, From, Found);
if not Found then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Store.Load (DB, Storage, File);
Into := ADO.Create_Blob (AWA.Storages.Get_Path (File));
end;
end if;
end Load;
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File) is
use type Stores.Store_Access;
use type Models.Storage_Type;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.Queries.Context;
Found : Boolean;
Storage : AWA.Storages.Models.Storage_Ref;
Local : AWA.Storages.Models.Store_Local_Ref;
Store : Stores.Store_Access;
begin
if Mode = READ then
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Local);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Local.Find (DB, Query, Found);
if Found then
Into.Path := Local.Get_Path;
return;
end if;
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Storage);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Storage.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
Ctx.Start;
Store := Storage_Service'Class (Service).Get_Store (Storage.Get_Storage);
Store.Load (Session => DB,
From => Storage,
Into => Into);
Ctx.Commit;
end Get_Local_File;
procedure Create_Local_File (Service : in Storage_Service;
Into : out Storage_File) is
begin
null;
end Create_Local_File;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class) is
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Id : constant ADO.Identifier := ADO.Objects.Get_Value (Storage.Get_Key);
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Id));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Id);
Ctx.Start;
Storage_Lifecycle.Notify_Delete (Service, Storage);
Storage.Delete (DB);
Ctx.Commit;
end Delete;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier) is
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
S : AWA.Storages.Models.Storage_Ref;
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (AWA.Storages.Models.Query_Storage_Delete_Local);
Store : Stores.Store_Access;
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Storage));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Storage);
Ctx.Start;
S.Load (Id => Storage, Session => DB);
Store := Storage_Service'Class (Service).Get_Store (S.Get_Storage);
if Store = null then
Log.Error ("There is no store associated with storage item {0}",
ADO.Identifier'Image (Storage));
else
Store.Delete (DB, S);
end if;
Storage_Lifecycle.Notify_Delete (Service, S);
-- Delete the storage instance and all storage that refer to it.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Storages.Models.STORAGE_TABLE);
begin
Stmt.Set_Filter (Filter => "id = ? OR original_id = ?");
Stmt.Add_Param (Value => Storage);
Stmt.Add_Param (Value => Storage);
Stmt.Execute;
end;
-- Delete the local storage instances.
Query.Bind_Param ("store_id", Storage);
Query.Execute;
S.Delete (DB);
Ctx.Commit;
end Delete;
end AWA.Storages.Services;
|
Use the Check permission by using the database object so that we can check for null object
|
Use the Check permission by using the database object so that we can check for null object
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
066f4261c49b8adee552222a34c14f383d7bc95c
|
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.ads
|
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.ads
|
-----------------------------------------------------------------------
-- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client
-- Copyright (C) 2012, 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.Strings.Unbounded;
with Ada.Finalization;
with Util.Properties;
with AWS.SMTP;
with AWS.SMTP.Authentication.Plain;
private with AWS.Attachments;
-- The <b>AWA.Mail.Clients.AWS_SMTP</b> package provides an implementation of the
-- mail client interfaces on top of AWS SMTP client API.
package AWA.Mail.Clients.AWS_SMTP is
NAME : constant String := "smtp";
-- ------------------------------
-- Mail Message
-- ------------------------------
-- The <b>Mail_Message</b> represents an abstract mail message that can be initialized
-- before being sent.
type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with private;
type AWS_Mail_Message_Access is access all AWS_Mail_Message'Class;
-- 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);
-- 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);
-- Set the subject of the message.
overriding
procedure Set_Subject (Message : in out AWS_Mail_Message;
Subject : in String);
-- 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);
-- 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);
-- Send the email message.
overriding
procedure Send (Message : in out AWS_Mail_Message);
-- Deletes the mail message.
overriding
procedure Finalize (Message : in out AWS_Mail_Message);
-- ------------------------------
-- Mail Manager
-- ------------------------------
-- The <b>Mail_Manager</b> is the entry point to create a new mail message
-- and be able to send it.
type AWS_Mail_Manager is new Mail_Manager with private;
type AWS_Mail_Manager_Access is access all AWS_Mail_Manager'Class;
-- 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;
-- Create a new mail message.
overriding
function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access;
private
type Recipients_Access is access all AWS.SMTP.Recipients;
type Recipients_Array is array (Recipient_Type) of Recipients_Access;
type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with record
Manager : AWS_Mail_Manager_Access;
From : AWS.SMTP.E_Mail_Data;
Subject : Ada.Strings.Unbounded.Unbounded_String;
To : Recipients_Array;
Attachments : AWS.Attachments.List;
end record;
type AWS_Mail_Manager is new Mail_Manager with record
Self : AWS_Mail_Manager_Access;
Server : AWS.SMTP.Receiver;
Creds : aliased AWS.SMTP.Authentication.Plain.Credential;
Port : Positive := 25;
Enable : Boolean := True;
Secure : Boolean := False;
Auth : Boolean := False;
end record;
procedure Initialize (Client : in out AWS_Mail_Manager'Class;
Props : in Util.Properties.Manager'Class);
end AWA.Mail.Clients.AWS_SMTP;
|
-----------------------------------------------------------------------
-- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client
-- Copyright (C) 2012, 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.Strings.Unbounded;
with Ada.Finalization;
with Util.Properties;
with AWS.SMTP;
with AWS.SMTP.Authentication.Plain;
private with AWS.Attachments;
-- The <b>AWA.Mail.Clients.AWS_SMTP</b> package provides an implementation of the
-- mail client interfaces on top of AWS SMTP client API.
package AWA.Mail.Clients.AWS_SMTP is
NAME : constant String := "smtp";
-- ------------------------------
-- Mail Message
-- ------------------------------
-- The <b>Mail_Message</b> represents an abstract mail message that can be initialized
-- before being sent.
type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with private;
type AWS_Mail_Message_Access is access all AWS_Mail_Message'Class;
-- 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);
-- 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);
-- Set the subject of the message.
overriding
procedure Set_Subject (Message : in out AWS_Mail_Message;
Subject : in String);
-- 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);
-- 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);
-- Add a file attachment.
overriding
procedure Add_File_Attachment (Message : in out AWS_Mail_Message;
Filename : in String;
Content_Id : in String;
Content_Type : in String);
-- Send the email message.
overriding
procedure Send (Message : in out AWS_Mail_Message);
-- Deletes the mail message.
overriding
procedure Finalize (Message : in out AWS_Mail_Message);
-- ------------------------------
-- Mail Manager
-- ------------------------------
-- The <b>Mail_Manager</b> is the entry point to create a new mail message
-- and be able to send it.
type AWS_Mail_Manager is new Mail_Manager with private;
type AWS_Mail_Manager_Access is access all AWS_Mail_Manager'Class;
-- 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;
-- Create a new mail message.
overriding
function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access;
private
type Recipients_Access is access all AWS.SMTP.Recipients;
type Recipients_Array is array (Recipient_Type) of Recipients_Access;
type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with record
Manager : AWS_Mail_Manager_Access;
From : AWS.SMTP.E_Mail_Data;
Subject : Ada.Strings.Unbounded.Unbounded_String;
To : Recipients_Array;
Attachments : AWS.Attachments.List;
end record;
type AWS_Mail_Manager is new Mail_Manager with record
Self : AWS_Mail_Manager_Access;
Server : AWS.SMTP.Receiver;
Creds : aliased AWS.SMTP.Authentication.Plain.Credential;
Port : Positive := 25;
Enable : Boolean := True;
Secure : Boolean := False;
Auth : Boolean := False;
end record;
procedure Initialize (Client : in out AWS_Mail_Manager'Class;
Props : in Util.Properties.Manager'Class);
end AWA.Mail.Clients.AWS_SMTP;
|
Declare the Add_File_Attachment procedure
|
Declare the Add_File_Attachment procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
bf427c37341d9b2ab51f01f0c19ef76176dd96c5
|
regtests/util-properties-tests.adb
|
regtests/util-properties-tests.adb
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 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 Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
T.Assert (Exists (Props, +("test")) = False,
"Invalid properties");
T.Assert (Props.Is_Empty, "Property manager should be empty");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted");
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
procedure Test_Load_Ini_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
V := Props.Get_Value ("mysqld");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
declare
P : Properties.Manager;
begin
P := Props.Get ("mysqld");
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
P := Props.Get ("mysqld_safe");
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
declare
P : Properties.Manager with Unreferenced;
begin
P := Props.Get ("bad");
T.Fail ("No exception raised for Get()");
exception
when NO_PROPERTY =>
null;
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf");
raise;
end Test_Load_Ini_Property;
procedure Test_Save_Properties (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties");
begin
declare
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
Props.Set ("New-Property", "Some-Value");
Props.Remove ("mysqld");
T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed");
Props.Save_Properties (Path);
end;
declare
Props : Properties.Manager;
V : Util.Properties.Value;
P : Properties.Manager;
begin
Props.Load_Properties (Path => Path);
T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)");
T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
end Test_Save_Properties;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)",
Test_Load_Ini_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties",
Test_Save_Properties'Access);
end Add_Tests;
end Util.Properties.Tests;
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 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 Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
T.Assert (Exists (Props, +("test")) = False,
"Invalid properties");
T.Assert (Props.Is_Empty, "Property manager should be empty");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
declare
V : constant String := Props.Get (+("test"));
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
declare
V : constant Unbounded_String := Props.Get (+("test"));
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
begin
V := Props.Get (+("missing"));
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted");
-- Check exception on Get returning a String.
begin
declare
S : constant String := Props.Get ("missing");
pragma Unreferenced (S);
begin
T.Fail ("Exception NO_PROPERTY was not raised");
end;
exception
when NO_PROPERTY =>
null;
end;
-- Check exception on Get returning a String.
begin
declare
S : constant String := Props.Get (+("missing"));
pragma Unreferenced (S);
begin
T.Fail ("Exception NO_PROPERTY was not raised");
end;
exception
when NO_PROPERTY =>
null;
end;
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
procedure Test_Load_Ini_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
V := Props.Get_Value ("mysqld");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
declare
P : Properties.Manager;
begin
P := Props.Get ("mysqld");
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
P := Props.Get ("mysqld_safe");
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
declare
P : Properties.Manager with Unreferenced;
begin
P := Props.Get ("bad");
T.Fail ("No exception raised for Get()");
exception
when NO_PROPERTY =>
null;
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf");
raise;
end Test_Load_Ini_Property;
procedure Test_Save_Properties (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties");
begin
declare
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
Props.Set ("New-Property", "Some-Value");
Props.Remove ("mysqld");
T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed");
Props.Save_Properties (Path);
end;
declare
Props : Properties.Manager;
V : Util.Properties.Value;
P : Properties.Manager;
begin
Props.Load_Properties (Path => Path);
T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)");
T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
end Test_Save_Properties;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)",
Test_Load_Ini_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties",
Test_Save_Properties'Access);
end Add_Tests;
end Util.Properties.Tests;
|
Add more tests on Get functions
|
Add more tests on Get functions
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
48e0eb8cbe886076a3c46238dbc331afbcf5d1f1
|
src/natools-web-list_templates.adb
|
src/natools-web-list_templates.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.Static_Maps.Web.List_Templates;
package body Natools.Web.List_Templates is
procedure Execute_Atom
(State : in out Parameters;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom);
procedure Execute_Expression
(State : in out Parameters;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
---------------------------
-- Parameter Interpreter --
---------------------------
procedure Execute_Expression
(State : in out Parameters;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
package Commands renames Natools.Static_Maps.Web.List_Templates;
package Constructors renames Natools.S_Expressions.Atom_Ref_Constructors;
use type S_Expressions.Events.Event;
begin
case Commands.To_Command (S_Expressions.To_String (Name)) is
when Commands.Unknown_Command =>
null;
when Commands.Backward =>
State.Going := Backward;
when Commands.Ellipsis_Prefix =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
State.Ellipsis_Prefix
:= Constructors.Create (Arguments.Current_Atom);
end if;
when Commands.Ellipsis_Suffix =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
State.Ellipsis_Suffix
:= Constructors.Create (Arguments.Current_Atom);
end if;
when Commands.Forward =>
State.Going := Forward;
when Commands.Length_Limit =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
begin
State.Limit := Count'Value (S_Expressions.To_String
(Arguments.Current_Atom));
exception
when Constraint_Error =>
State.Limit := 0;
end;
end if;
when Commands.Template =>
State.Template := S_Expressions.Caches.Move (Arguments);
end case;
end Execute_Expression;
procedure Execute_Atom
(State : in out Parameters;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom)
is
pragma Unreferenced (Context);
package Commands renames Natools.Static_Maps.Web.List_Templates;
begin
case Commands.To_Command (S_Expressions.To_String (Name)) is
when Commands.Unknown_Command =>
null;
when Commands.Backward =>
State.Going := Backward;
when Commands.Ellipsis_Prefix =>
State.Ellipsis_Prefix.Reset;
when Commands.Ellipsis_Suffix =>
State.Ellipsis_Suffix.Reset;
when Commands.Forward =>
State.Going := Forward;
when Commands.Length_Limit =>
State.Limit := 0;
when Commands.Template =>
null;
end case;
end Execute_Atom;
procedure Read is new Natools.S_Expressions.Interpreter_Loop
(Parameters, Meaningless_Type, Execute_Expression, Execute_Atom);
procedure Read_Parameters
(Object : in out Parameters;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Read (Expression, Object, Meaningless_Value);
end Read_Parameters;
function Read_Parameters
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Parameters
is
Result : Parameters;
begin
Read_Parameters (Result, Expression);
return Result;
end Read_Parameters;
-----------------------
-- Generic Rendering --
-----------------------
procedure Render
(Exchange : in out Sites.Exchange;
Iterator : in Iterators.Reversible_Iterator'Class;
Param : in Parameters)
is
procedure Loop_Body
(Position : in Iterators.Cursor; Exit_Loop : out Boolean);
Rendered : Count := 0;
procedure Loop_Body
(Position : in Iterators.Cursor; Exit_Loop : out Boolean) is
begin
Exit_Loop := False;
declare
Template_Copy : S_Expressions.Caches.Cursor := Param.Template;
begin
Render (Exchange, Position, Template_Copy);
end;
Rendered := Rendered + 1;
if Param.Limit > 0 and then Rendered >= Param.Limit then
if not Param.Ellipsis_Suffix.Is_Empty then
Exchange.Append (Param.Ellipsis_Suffix.Query);
end if;
Exit_Loop := True;
end if;
end Loop_Body;
Exit_Loop : Boolean;
begin
if Param.Limit > 0 and then not Param.Ellipsis_Prefix.Is_Empty then
declare
Seen : Count := 0;
begin
for I in Iterator loop
Seen := Seen + 1;
exit when Seen > Param.Limit;
end loop;
if Seen > Param.Limit then
Exchange.Append (Param.Ellipsis_Prefix.Query);
end if;
end;
end if;
case Param.Going is
when Forward =>
for Position in Iterator loop
Loop_Body (Position, Exit_Loop);
exit when Exit_Loop;
end loop;
when Backward =>
for Position in reverse Iterator loop
Loop_Body (Position, Exit_Loop);
exit when Exit_Loop;
end loop;
end case;
end Render;
end Natools.Web.List_Templates;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.Static_Maps.Web.List_Templates;
package body Natools.Web.List_Templates is
procedure Execute_Atom
(State : in out Parameters;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom);
procedure Execute_Expression
(State : in out Parameters;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
---------------------------
-- Parameter Interpreter --
---------------------------
procedure Execute_Expression
(State : in out Parameters;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
package Commands renames Natools.Static_Maps.Web.List_Templates;
package Constructors renames Natools.S_Expressions.Atom_Ref_Constructors;
use type S_Expressions.Events.Event;
begin
case Commands.To_Command (S_Expressions.To_String (Name)) is
when Commands.Unknown_Command =>
null;
when Commands.Backward =>
State.Going := Backward;
when Commands.Ellipsis_Prefix =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
State.Ellipsis_Prefix
:= Constructors.Create (Arguments.Current_Atom);
end if;
when Commands.Ellipsis_Suffix =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
State.Ellipsis_Suffix
:= Constructors.Create (Arguments.Current_Atom);
end if;
when Commands.Forward =>
State.Going := Forward;
when Commands.Length_Limit =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
begin
State.Limit := Count'Value (S_Expressions.To_String
(Arguments.Current_Atom));
exception
when Constraint_Error =>
State.Limit := 0;
end;
end if;
when Commands.Template =>
State.Template := S_Expressions.Caches.Move (Arguments);
end case;
end Execute_Expression;
procedure Execute_Atom
(State : in out Parameters;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom)
is
pragma Unreferenced (Context);
package Commands renames Natools.Static_Maps.Web.List_Templates;
begin
case Commands.To_Command (S_Expressions.To_String (Name)) is
when Commands.Unknown_Command =>
null;
when Commands.Backward =>
State.Going := Backward;
when Commands.Ellipsis_Prefix =>
State.Ellipsis_Prefix.Reset;
when Commands.Ellipsis_Suffix =>
State.Ellipsis_Suffix.Reset;
when Commands.Forward =>
State.Going := Forward;
when Commands.Length_Limit =>
State.Limit := 0;
when Commands.Template =>
null;
end case;
end Execute_Atom;
procedure Read is new Natools.S_Expressions.Interpreter_Loop
(Parameters, Meaningless_Type, Execute_Expression, Execute_Atom);
procedure Read_Parameters
(Object : in out Parameters;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Read (Expression, Object, Meaningless_Value);
end Read_Parameters;
function Read_Parameters
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Parameters
is
Result : Parameters;
begin
Read_Parameters (Result, Expression);
return Result;
end Read_Parameters;
-----------------------
-- Generic Rendering --
-----------------------
procedure Render
(Exchange : in out Sites.Exchange;
Iterator : in Iterators.Reversible_Iterator'Class;
Param : in Parameters)
is
procedure Loop_Body
(Position : in Iterators.Cursor; Exit_Loop : out Boolean);
Rendered : Count := 0;
procedure Loop_Body
(Position : in Iterators.Cursor; Exit_Loop : out Boolean) is
begin
if Param.Limit > 0 and then Rendered >= Param.Limit then
if not Param.Ellipsis_Suffix.Is_Empty then
Exchange.Append (Param.Ellipsis_Suffix.Query);
end if;
Exit_Loop := True;
return;
end if;
Exit_Loop := False;
declare
Template_Copy : S_Expressions.Caches.Cursor := Param.Template;
begin
Render (Exchange, Position, Template_Copy);
end;
Rendered := Rendered + 1;
end Loop_Body;
Exit_Loop : Boolean;
begin
if Param.Limit > 0 and then not Param.Ellipsis_Prefix.Is_Empty then
declare
Seen : Count := 0;
begin
for I in Iterator loop
Seen := Seen + 1;
exit when Seen > Param.Limit;
end loop;
if Seen > Param.Limit then
Exchange.Append (Param.Ellipsis_Prefix.Query);
end if;
end;
end if;
case Param.Going is
when Forward =>
for Position in Iterator loop
Loop_Body (Position, Exit_Loop);
exit when Exit_Loop;
end loop;
when Backward =>
for Position in reverse Iterator loop
Loop_Body (Position, Exit_Loop);
exit when Exit_Loop;
end loop;
end case;
end Render;
end Natools.Web.List_Templates;
|
fix incorrect display of ellipsis suffix when the list has exactly the maximum length
|
list_templates: fix incorrect display of ellipsis suffix when the list has exactly the maximum length
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
450766bdeda4b9362b843dd3d222b7ab05037bd0
|
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.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
-- ------------------------------
-- 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 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
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
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);
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;
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.Identifier (Util.Beans.Objects.To_Integer (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.Identifier (Util.Beans.Objects.To_Integer (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;
-- ------------------------------
-- 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_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
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.all, Session, Query);
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);
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;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
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.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);
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;
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.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
-- ------------------------------
-- 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 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
From.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
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);
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;
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.Identifier (Util.Beans.Objects.To_Integer (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.Identifier (Util.Beans.Objects.To_Integer (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;
-- ------------------------------
-- 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_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
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.all, Session, Query);
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 : ADO.Identifier := ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (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;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
Load the questions tags when the question and answers are loaded
|
Load the questions tags when the question and answers are loaded
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6f02aa8405e86a6c31b0338169d9674c74e1a3c9
|
awa/src/awa-permissions-services.ads
|
awa/src/awa-permissions-services.ads
|
-----------------------------------------------------------------------
-- awa-permissions-services -- Permissions controller
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Applications;
with ADO;
with ADO.Sessions;
with ADO.Objects;
with Security.Permissions;
with Security.Contexts;
package AWA.Permissions.Services is
type Permission_Manager is new Security.Permissions.Permission_Manager with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
-- Get the permission manager associated with the security context.
-- Returns null if there is none.
function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class)
return Permission_Manager_Access;
-- Get the application instance.
function Get_Application (Manager : in Permission_Manager)
return AWA.Applications.Application_Access;
-- Set the application instance.
procedure Set_Application (Manager : in out Permission_Manager;
App : in AWA.Applications.Application_Access);
-- Add a permission for the current user to access the entity identified by
-- <b>Entity</b> and <b>Kind</b>.
procedure Add_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type);
-- Check that the current user has the specified permission.
-- Raise NO_PERMISSION exception if the user does not have the permission.
procedure Check_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type);
-- Read the policy file
overriding
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b> which is of type <b>Kind</b>.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type := READ);
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b>.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Objects.Object_Ref'Class;
Permission : in Permission_Type := READ);
-- Create a permission manager for the given application.
function Create_Permission_Manager (App : in AWA.Applications.Application_Access)
return Security.Permissions.Permission_Manager_Access;
private
type Permission_Manager is new Security.Permissions.Permission_Manager with record
App : AWA.Applications.Application_Access := null;
end record;
end AWA.Permissions.Services;
|
-----------------------------------------------------------------------
-- awa-permissions-services -- Permissions controller
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Applications;
with ADO;
with ADO.Sessions;
with ADO.Objects;
with Security.Policies;
with Security.Contexts;
package AWA.Permissions.Services is
type Permission_Manager is new Security.Policies.Policy_Manager with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
-- Get the permission manager associated with the security context.
-- Returns null if there is none.
function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class)
return Permission_Manager_Access;
-- Get the application instance.
function Get_Application (Manager : in Permission_Manager)
return AWA.Applications.Application_Access;
-- Set the application instance.
procedure Set_Application (Manager : in out Permission_Manager;
App : in AWA.Applications.Application_Access);
-- Add a permission for the current user to access the entity identified by
-- <b>Entity</b> and <b>Kind</b>.
procedure Add_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type);
-- Check that the current user has the specified permission.
-- Raise NO_PERMISSION exception if the user does not have the permission.
procedure Check_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type);
-- Read the policy file
overriding
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b> which is of type <b>Kind</b>.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type := READ);
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b>.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Objects.Object_Ref'Class;
Permission : in Permission_Type := READ);
-- Create a permission manager for the given application.
function Create_Permission_Manager (App : in AWA.Applications.Application_Access)
return Security.Policies.Policy_Manager_Access;
private
type Permission_Manager is new Security.Policies.Policy_Manager with record
App : AWA.Applications.Application_Access := null;
end record;
end AWA.Permissions.Services;
|
Use the Security.Policies package
|
Use the Security.Policies package
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
68e500254e298c5edf65df57f0e128d5fa25b804
|
regtests/util-log-tests.adb
|
regtests/util-log-tests.adb
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011, 2013, 2015, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Directories;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Files;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name,
"Get_Level_Name function is invalid");
end Test_Log;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report", 1000);
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Info message (output)", 1000);
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Debug message (no output)", 10_000);
end;
end Test_Log_Perf;
-- ------------------------------
-- Test appending the log on several log files
-- ------------------------------
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", "test" & Id & ".log");
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := "test" & Id & ".log";
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file "
& Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_File_Appender_Modes (T : in out Test) is
use Ada.Directories;
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test-append.log");
Props.Set ("log4j.appender.test.append", "true");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.appender.test_global", "File");
Props.Set ("log4j.appender.test_global.File", "test-append-global.log");
Props.Set ("log4j.appender.test_global.append", "false");
Props.Set ("log4j.appender.test_global.immediateFlush", "false");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG");
Props.Set ("log4j.rootCategory", "DEBUG,test_global,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Error ("This is the error test message");
end;
Props.Set ("log4j.appender.test_append", "File");
Props.Set ("log4j.appender.test_append.File", "test-append2.log");
Props.Set ("log4j.appender.test_append.append", "true");
Props.Set ("log4j.appender.test_append.immediateFlush", "true");
Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global");
Util.Log.Loggers.Initialize (Props);
declare
L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file");
begin
L1.Info ("L1-1 Writing a info message");
L2.Info ("L2-2 {0}: {1}", "Parameter", "Value");
L1.Info ("L1-3 Done");
L2.Error ("L2-4 This is the error test2 message");
end;
Props.Set ("log4j.appender.test_append.append", "plop");
Props.Set ("log4j.appender.test_append.immediateFlush", "falsex");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
T.Assert (Ada.Directories.Size ("test-append.log") > 100,
"Log file test-append.log is empty");
T.Assert (Ada.Directories.Size ("test-append2.log") > 100,
"Log file test-append2.log is empty");
T.Assert (Ada.Directories.Size ("test-append-global.log") > 100,
"Log file test-append.log is empty");
end Test_File_Appender_Modes;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_Console_Appender (T : in out Test) is
Props : Util.Properties.Manager;
File : Ada.Text_IO.File_Type;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, "test_err.log");
Ada.Text_IO.Set_Error (File);
Props.Set ("log4j.appender.test_console", "Console");
Props.Set ("log4j.appender.test_console.stderr", "true");
Props.Set ("log4j.appender.test_console.level", "WARN");
Props.Set ("log4j.rootCategory", "INFO,test_console");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Info ("INFO MESSAGE!");
L.Warn ("WARN MESSAGE!");
L.Error ("This {0} {1} {2} test message", "is", "the", "error");
end;
Ada.Text_IO.Flush (Ada.Text_IO.Current_Error);
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
Ada.Text_IO.Close (File);
Util.Files.Read_File ("test_err.log", Content);
Util.Tests.Assert_Matches (T, ".*WARN MESSAGE!", Content,
"Invalid console log (WARN)");
Util.Tests.Assert_Matches (T, ".*This is the error test message", Content,
"Invalid console log (ERROR)");
exception
when others =>
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
raise;
end Test_Console_Appender;
procedure Test_Missing_Config (T : in out Test) is
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
Util.Log.Loggers.Initialize ("plop");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Missing_Config;
procedure Test_Log_Traceback (T : in out Test) is
Props : Util.Properties.Manager;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test-traceback.log");
Props.Set ("log4j.appender.test.append", "false");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.rootCategory", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Error ("This is the error test message");
raise Constraint_Error with "Test";
exception
when E : others =>
L.Error ("Something wrong", E, True);
end;
Props.Set ("log4j.rootCategory", "DEBUG,console");
Props.Set ("log4j.appender.console", "Console");
Util.Log.Loggers.Initialize (Props);
Util.Files.Read_File ("test-traceback.log", Content);
Util.Tests.Assert_Matches (T, ".*Something wrong: Exception CONSTRAINT_ERROR:", Content,
"Invalid console log (ERROR)");
end Test_Log_Traceback;
package Caller is new Util.Test_Caller (Test, "Log");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Error",
Test_Log_Traceback'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Initialize",
Test_Missing_Config'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)",
Test_File_Appender_Modes'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.Console",
Test_Console_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
-----------------------------------------------------------------------
-- log.tests -- Unit tests for loggers
-- Copyright (C) 2009, 2010, 2011, 2013, 2015, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Directories;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Log;
with Util.Log.Loggers;
with Util.Files;
with Util.Properties;
with Util.Measures;
package body Util.Log.Tests is
Log : constant Loggers.Logger := Loggers.Create ("util.log.test");
procedure Test_Log (T : in out Test) is
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
L.Set_Level (DEBUG_LEVEL);
Log.Info ("My log message");
Log.Error ("My error message");
Log.Debug ("A debug message Not printed");
L.Info ("An info message");
L.Info ("A {0} {1} {2} {3}", "info", "message", "not", "printed");
L.Debug ("A debug message on logger 'L'");
Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name,
"Get_Level_Name function is invalid");
end Test_Log;
procedure Test_Debug (T : in out Test) is
L : Loggers.Logger := Loggers.Create ("util.log.test.debug");
C : Ada.Strings.Unbounded.Unbounded_String;
begin
L.Set_Level (DEBUG_LEVEL);
L.Info ("My log message");
L.Error ("My error message");
L.Debug ("A {0} {1} {2} {3}", "debug", "message", "not", "printed");
L.Debug ("A {0} {1} {2} {3}", C, "message", "printed");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name,
"Get_Level_Name function is invalid");
end Test_Debug;
-- Test configuration and creation of file
procedure Test_File_Appender (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
end;
end Test_File_Appender;
procedure Test_Log_Perf (T : in out Test) is
pragma Unreferenced (T);
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test.log");
Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
for I in 1 .. 1000 loop
declare
S : Util.Measures.Stamp;
begin
Util.Measures.Report (S, "Util.Measures.Report", 1000);
end;
end loop;
declare
L : Loggers.Logger := Loggers.Create ("util.log.test.perf");
S : Util.Measures.Stamp;
begin
L.Set_Level (DEBUG_LEVEL);
for I in 1 .. 1000 loop
L.Info ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Info message (output)", 1000);
L.Set_Level (INFO_LEVEL);
for I in 1 .. 10_000 loop
L.Debug ("My log message: {0}: {1}", "A message",
"A second parameter");
end loop;
Util.Measures.Report (S, "Log.Debug message (no output)", 10_000);
end;
end Test_Log_Perf;
-- ------------------------------
-- Test appending the log on several log files
-- ------------------------------
procedure Test_List_Appender (T : in out Test) is
use Ada.Strings;
use Ada.Directories;
Props : Util.Properties.Manager;
begin
for I in 1 .. 10 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Name : constant String := "log4j.appender.test" & Id;
begin
Props.Set (Name, "File");
Props.Set (Name & ".File", "test" & Id & ".log");
Props.Set (Name & ".layout", "date-level-message");
if I > 5 then
Props.Set (Name & ".level", "INFO");
end if;
end;
end loop;
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Props.Set ("log4j.logger.util.log.test.file",
"DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
end;
-- Check that we have non empty log files (up to test8.log).
for I in 1 .. 8 loop
declare
Id : constant String := Fixed.Trim (Integer'Image (I), Both);
Path : constant String := "test" & Id & ".log";
begin
T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found");
if I > 5 then
T.Assert (Ada.Directories.Size (Path) < 100, "Log file "
& Path & " should be empty");
else
T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty");
end if;
end;
end loop;
end Test_List_Appender;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_File_Appender_Modes (T : in out Test) is
use Ada.Directories;
Props : Util.Properties.Manager;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test-append.log");
Props.Set ("log4j.appender.test.append", "true");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.appender.test_global", "File");
Props.Set ("log4j.appender.test_global.File", "test-append-global.log");
Props.Set ("log4j.appender.test_global.append", "false");
Props.Set ("log4j.appender.test_global.immediateFlush", "false");
Props.Set ("log4j.logger.util.log.test.file", "DEBUG");
Props.Set ("log4j.rootCategory", "DEBUG,test_global,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Error ("This is the error test message");
end;
Props.Set ("log4j.appender.test_append", "File");
Props.Set ("log4j.appender.test_append.File", "test-append2.log");
Props.Set ("log4j.appender.test_append.append", "true");
Props.Set ("log4j.appender.test_append.immediateFlush", "true");
Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global");
Util.Log.Loggers.Initialize (Props);
declare
L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file");
begin
L1.Info ("L1-1 Writing a info message");
L2.Info ("L2-2 {0}: {1}", "Parameter", "Value");
L1.Info ("L1-3 Done");
L2.Error ("L2-4 This is the error test2 message");
end;
Props.Set ("log4j.appender.test_append.append", "plop");
Props.Set ("log4j.appender.test_append.immediateFlush", "falsex");
Props.Set ("log4j.rootCategory", "DEBUG, test.log");
Util.Log.Loggers.Initialize (Props);
T.Assert (Ada.Directories.Size ("test-append.log") > 100,
"Log file test-append.log is empty");
T.Assert (Ada.Directories.Size ("test-append2.log") > 100,
"Log file test-append2.log is empty");
T.Assert (Ada.Directories.Size ("test-append-global.log") > 100,
"Log file test-append.log is empty");
end Test_File_Appender_Modes;
-- ------------------------------
-- Test file appender with different modes.
-- ------------------------------
procedure Test_Console_Appender (T : in out Test) is
Props : Util.Properties.Manager;
File : Ada.Text_IO.File_Type;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, "test_err.log");
Ada.Text_IO.Set_Error (File);
Props.Set ("log4j.appender.test_console", "Console");
Props.Set ("log4j.appender.test_console.stderr", "true");
Props.Set ("log4j.appender.test_console.level", "WARN");
Props.Set ("log4j.rootCategory", "INFO,test_console");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Debug ("Writing a debug message");
L.Debug ("{0}: {1}", "Parameter", "Value");
L.Debug ("Done");
L.Info ("INFO MESSAGE!");
L.Warn ("WARN MESSAGE!");
L.Error ("This {0} {1} {2} test message", "is", "the", "error");
end;
Ada.Text_IO.Flush (Ada.Text_IO.Current_Error);
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
Ada.Text_IO.Close (File);
Util.Files.Read_File ("test_err.log", Content);
Util.Tests.Assert_Matches (T, ".*WARN MESSAGE!", Content,
"Invalid console log (WARN)");
Util.Tests.Assert_Matches (T, ".*This is the error test message", Content,
"Invalid console log (ERROR)");
exception
when others =>
Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error);
raise;
end Test_Console_Appender;
procedure Test_Missing_Config (T : in out Test) is
L : constant Loggers.Logger := Loggers.Create ("util.log.test.debug");
begin
Util.Log.Loggers.Initialize ("plop");
L.Info ("An info message");
L.Debug ("A debug message on logger 'L'");
end Test_Missing_Config;
procedure Test_Log_Traceback (T : in out Test) is
Props : Util.Properties.Manager;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Props.Set ("log4j.appender.test", "File");
Props.Set ("log4j.appender.test.File", "test-traceback.log");
Props.Set ("log4j.appender.test.append", "false");
Props.Set ("log4j.appender.test.immediateFlush", "true");
Props.Set ("log4j.rootCategory", "DEBUG,test");
Util.Log.Loggers.Initialize (Props);
declare
L : constant Loggers.Logger := Loggers.Create ("util.log.test.file");
begin
L.Error ("This is the error test message");
raise Constraint_Error with "Test";
exception
when E : others =>
L.Error ("Something wrong", E, True);
end;
Props.Set ("log4j.rootCategory", "DEBUG,console");
Props.Set ("log4j.appender.console", "Console");
Util.Log.Loggers.Initialize (Props);
Util.Files.Read_File ("test-traceback.log", Content);
Util.Tests.Assert_Matches (T, ".*Something wrong: Exception CONSTRAINT_ERROR:", Content,
"Invalid console log (ERROR)");
end Test_Log_Traceback;
package Caller is new Util.Test_Caller (Test, "Log");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug",
Test_Debug'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level",
Test_Log'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Error",
Test_Log_Traceback'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Initialize",
Test_Missing_Config'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender",
Test_File_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)",
Test_File_Appender_Modes'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender",
Test_List_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Appenders.Console",
Test_Console_Appender'Access);
Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)",
Test_Log_Perf'Access);
end Add_Tests;
end Util.Log.Tests;
|
Add Test_Debug procedure to test more Debug operations
|
Add Test_Debug procedure to test more Debug operations
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
98881d4ade4e7bf82ad53ab11cd7a2b3d915b7cf
|
matp/src/mat-expressions.adb
|
matp/src/mat-expressions.adb
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with MAT.Expressions.Parser;
package body MAT.Expressions is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Node_Type,
Name => Node_Type_Access);
-- Destroy recursively the node, releasing the storage.
procedure Destroy (Node : in out Node_Type_Access);
-- ------------------------------
-- Create a NOT expression node.
-- ------------------------------
function Create_Not (Expr : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NOT,
Expr => Expr.Node);
Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter);
return Result;
end Create_Not;
-- ------------------------------
-- Create a AND expression node.
-- ------------------------------
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_AND,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_And;
-- ------------------------------
-- Create a OR expression node.
-- ------------------------------
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_OR,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_Or;
-- ------------------------------
-- Create an INSIDE expression node.
-- ------------------------------
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_INSIDE,
Name => Name,
Inside => Kind);
return Result;
end Create_Inside;
-- ------------------------------
-- Create an size range expression node.
-- ------------------------------
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_SIZE,
Min_Size => Min,
Max_Size => Max);
return Result;
end Create_Size;
-- ------------------------------
-- Create an addr range expression node.
-- ------------------------------
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_ADDR,
Min_Addr => Min,
Max_Addr => Max);
return Result;
end Create_Addr;
-- ------------------------------
-- Create an time range expression node.
-- ------------------------------
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_TIME,
Min_Time => Min,
Max_Time => Max);
return Result;
end Create_Time;
-- ------------------------------
-- Create a thread ID range expression node.
-- ------------------------------
function Create_Thread (Min : in MAT.Types.Target_Thread_Ref;
Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_THREAD,
Min_Thread => Min,
Max_Thread => Max);
return Result;
end Create_Thread;
-- ------------------------------
-- Create an event ID range expression node.
-- ------------------------------
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_EVENT,
Min_Event => Min,
Max_Event => Max);
return Result;
end Create_Event;
-- ------------------------------
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
begin
if Node.Node = null then
return True;
else
return Is_Selected (Node.Node.all, Addr, Allocation);
end if;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
begin
return Is_Selected (Node.Node.all, Event);
end Is_Selected;
-- ------------------------------
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Addr, Allocation);
when N_AND =>
return Is_Selected (Node.Left.all, Addr, Allocation)
and then Is_Selected (Node.Right.all, Addr, Allocation);
when N_OR =>
return Is_Selected (Node.Left.all, Addr, Allocation)
or else Is_Selected (Node.Right.all, Addr, Allocation);
when N_RANGE_SIZE =>
return Allocation.Size >= Node.Min_Size
and Allocation.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Addr >= Node.Min_Addr
and Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Allocation.Time >= Node.Min_Time
and Allocation.Time <= Node.Max_Time;
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
use type MAT.Types.Target_Thread_Ref;
use type MAT.Events.Targets.Event_Id_Type;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Event);
when N_AND =>
return Is_Selected (Node.Left.all, Event)
and then Is_Selected (Node.Right.all, Event);
when N_OR =>
return Is_Selected (Node.Left.all, Event)
or else Is_Selected (Node.Right.all, Event);
when N_RANGE_SIZE =>
return Event.Size >= Node.Min_Size
and Event.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Event.Addr >= Node.Min_Addr
and Event.Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Event.Time >= Node.Min_Time
and Event.Time <= Node.Max_Time;
when N_EVENT =>
return Event.Id >= Node.Min_Event
and Event.Id <= Node.Max_Event;
when N_THREAD =>
return Event.Thread >= Node.Min_Thread
and Event.Thread <= Node.Max_Thread;
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Parse the string and return the expression tree.
-- ------------------------------
function Parse (Expr : in String) return Expression_Type is
begin
return MAT.Expressions.Parser.Parse (Expr);
end Parse;
-- ------------------------------
-- Destroy recursively the node, releasing the storage.
-- ------------------------------
procedure Destroy (Node : in out Node_Type_Access) is
Release : Boolean;
begin
if Node /= null then
Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release);
if Release then
case Node.Kind is
when N_NOT =>
Destroy (Node.Expr);
when N_AND | N_OR =>
Destroy (Node.Left);
Destroy (Node.Right);
when others =>
null;
end case;
Free (Node);
else
Node := null;
end if;
end if;
end Destroy;
-- ------------------------------
-- Release the reference and destroy the expression tree if it was the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Destroy (Obj.Node);
end if;
end Finalize;
-- ------------------------------
-- Update the reference after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter);
end if;
end Adjust;
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with MAT.Expressions.Parser;
package body MAT.Expressions is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Node_Type,
Name => Node_Type_Access);
-- Destroy recursively the node, releasing the storage.
procedure Destroy (Node : in out Node_Type_Access);
-- ------------------------------
-- Create a NOT expression node.
-- ------------------------------
function Create_Not (Expr : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NOT,
Expr => Expr.Node);
Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter);
return Result;
end Create_Not;
-- ------------------------------
-- Create a AND expression node.
-- ------------------------------
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_AND,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_And;
-- ------------------------------
-- Create a OR expression node.
-- ------------------------------
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_OR,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_Or;
-- ------------------------------
-- Create an INSIDE expression node.
-- ------------------------------
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_INSIDE,
Name => Name,
Inside => Kind);
return Result;
end Create_Inside;
-- ------------------------------
-- Create an size range expression node.
-- ------------------------------
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_SIZE,
Min_Size => Min,
Max_Size => Max);
return Result;
end Create_Size;
-- ------------------------------
-- Create an addr range expression node.
-- ------------------------------
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_ADDR,
Min_Addr => Min,
Max_Addr => Max);
return Result;
end Create_Addr;
-- ------------------------------
-- Create an time range expression node.
-- ------------------------------
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_TIME,
Min_Time => Min,
Max_Time => Max);
return Result;
end Create_Time;
-- ------------------------------
-- Create a thread ID range expression node.
-- ------------------------------
function Create_Thread (Min : in MAT.Types.Target_Thread_Ref;
Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_THREAD,
Min_Thread => Min,
Max_Thread => Max);
return Result;
end Create_Thread;
-- ------------------------------
-- Create a event type expression check.
-- ------------------------------
function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type)
return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_TYPE,
Event_Kind => Event_Kind);
return Result;
end Create_Event_Type;
-- ------------------------------
-- Create an event ID range expression node.
-- ------------------------------
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_EVENT,
Min_Event => Min,
Max_Event => Max);
return Result;
end Create_Event;
-- ------------------------------
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
begin
if Node.Node = null then
return True;
else
return Is_Selected (Node.Node.all, Addr, Allocation);
end if;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
begin
return Is_Selected (Node.Node.all, Event);
end Is_Selected;
-- ------------------------------
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Addr, Allocation);
when N_AND =>
return Is_Selected (Node.Left.all, Addr, Allocation)
and then Is_Selected (Node.Right.all, Addr, Allocation);
when N_OR =>
return Is_Selected (Node.Left.all, Addr, Allocation)
or else Is_Selected (Node.Right.all, Addr, Allocation);
when N_RANGE_SIZE =>
return Allocation.Size >= Node.Min_Size
and Allocation.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Addr >= Node.Min_Addr
and Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Allocation.Time >= Node.Min_Time
and Allocation.Time <= Node.Max_Time;
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
use type MAT.Types.Target_Thread_Ref;
use type MAT.Events.Targets.Event_Id_Type;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Event);
when N_AND =>
return Is_Selected (Node.Left.all, Event)
and then Is_Selected (Node.Right.all, Event);
when N_OR =>
return Is_Selected (Node.Left.all, Event)
or else Is_Selected (Node.Right.all, Event);
when N_RANGE_SIZE =>
return Event.Size >= Node.Min_Size
and Event.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Event.Addr >= Node.Min_Addr
and Event.Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Event.Time >= Node.Min_Time
and Event.Time <= Node.Max_Time;
when N_EVENT =>
return Event.Id >= Node.Min_Event
and Event.Id <= Node.Max_Event;
when N_THREAD =>
return Event.Thread >= Node.Min_Thread
and Event.Thread <= Node.Max_Thread;
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Parse the string and return the expression tree.
-- ------------------------------
function Parse (Expr : in String) return Expression_Type is
begin
return MAT.Expressions.Parser.Parse (Expr);
end Parse;
-- ------------------------------
-- Destroy recursively the node, releasing the storage.
-- ------------------------------
procedure Destroy (Node : in out Node_Type_Access) is
Release : Boolean;
begin
if Node /= null then
Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release);
if Release then
case Node.Kind is
when N_NOT =>
Destroy (Node.Expr);
when N_AND | N_OR =>
Destroy (Node.Left);
Destroy (Node.Right);
when others =>
null;
end case;
Free (Node);
else
Node := null;
end if;
end if;
end Destroy;
-- ------------------------------
-- Release the reference and destroy the expression tree if it was the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Destroy (Obj.Node);
end if;
end Finalize;
-- ------------------------------
-- Update the reference after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter);
end if;
end Adjust;
end MAT.Expressions;
|
Implement Create_Event_Type to build a new expression node
|
Implement Create_Event_Type to build a new expression node
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
ca4d3a2a5539fe7d3ba4979703b9a86bd1473de1
|
src/sys/encoders/util-encoders-aes.ads
|
src/sys/encoders/util-encoders-aes.ads
|
-----------------------------------------------------------------------
-- util-encoders-aes -- AES encryption and decryption
-- 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 Interfaces;
private with Ada.Finalization;
-- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to
-- RFC3174 or [FIPS-180-1].
package Util.Encoders.AES is
type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR);
type Key_Type is private;
-- ------------------------------
-- ------------------------------
subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16);
AES_128_Length : constant := 16;
AES_192_Length : constant := 24;
AES_256_Length : constant := 32;
subtype AES_128_Key is Ada.Streams.Stream_Element_Array (1 .. 16);
subtype AES_192_Key is Ada.Streams.Stream_Element_Array (1 .. 24);
subtype AES_256_Key is Ada.Streams.Stream_Element_Array (1 .. 32);
type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32;
procedure Set_Encrypt_Key (Key : out Key_Type;
Data : in Secret_Key)
with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32;
procedure Set_Decrypt_Key (Key : out Key_Type;
Data : in Secret_Key)
with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32;
procedure Encrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Word_Block_Type;
Output : out Word_Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array;
Output : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Key : in Key_Type);
procedure Decrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Decrypt (Input : in Word_Block_Type;
Output : out Word_Block_Type;
Key : in Key_Type);
type Cipher is tagged limited private;
-- Set the encryption initialization vector before starting the encryption.
procedure Set_IV (E : in out Cipher;
IV : in Word_Block_Type);
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Encoder is new Cipher and Util.Encoders.Transformer with private;
-- Set the encryption key to use.
procedure Set_Key (E : in out Encoder;
Data : in Secret_Key;
Mode : in AES_Mode := CBC);
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Finish encoding the input array.
overriding
procedure Finish (E : in out Encoder;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset)
with Pre => Into'Length >= Block_Type'Length,
Post => Last = Into'First - 1 or Last = Into'First + Block_Type'Length - 1;
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Decoder is new Cipher and Util.Encoders.Transformer with private;
-- Set the decryption key to use.
procedure Set_Key (E : in out Decoder;
Data : in Secret_Key;
Mode : in AES_Mode := CBC);
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Finish encoding the input array.
overriding
procedure Finish (E : in out Decoder;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset);
private
use Interfaces;
type Block_Key is array (0 .. 59) of Unsigned_32;
type Key_Type is record
Key : Block_Key := (others => 0);
Rounds : Natural := 0;
end record;
type Cipher is limited new Ada.Finalization.Limited_Controlled with record
IV : Word_Block_Type;
Key : Key_Type;
Mode : AES_Mode := CBC;
Data_Count : Ada.Streams.Stream_Element_Offset := 0;
Data : Block_Type;
end record;
overriding
procedure Finalize (Object : in out Cipher);
type Encoder is new Cipher and Util.Encoders.Transformer with null record;
type Decoder is new Cipher and Util.Encoders.Transformer with null record;
end Util.Encoders.AES;
|
-----------------------------------------------------------------------
-- util-encoders-aes -- AES encryption and decryption
-- 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 Interfaces;
private with Ada.Finalization;
-- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to
-- RFC3174 or [FIPS-180-1].
package Util.Encoders.AES is
type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR);
type Key_Type is private;
-- ------------------------------
-- ------------------------------
subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16);
AES_128_Length : constant := 16;
AES_192_Length : constant := 24;
AES_256_Length : constant := 32;
subtype AES_128_Key is Ada.Streams.Stream_Element_Array (1 .. 16);
subtype AES_192_Key is Ada.Streams.Stream_Element_Array (1 .. 24);
subtype AES_256_Key is Ada.Streams.Stream_Element_Array (1 .. 32);
type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32;
procedure Set_Encrypt_Key (Key : out Key_Type;
Data : in Secret_Key)
with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32;
procedure Set_Decrypt_Key (Key : out Key_Type;
Data : in Secret_Key)
with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32;
procedure Encrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Word_Block_Type;
Output : out Word_Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array;
Output : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Key : in Key_Type);
procedure Decrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Decrypt (Input : in Word_Block_Type;
Output : out Word_Block_Type;
Key : in Key_Type);
type Cipher is tagged limited private;
-- Set the encryption initialization vector before starting the encryption.
procedure Set_IV (E : in out Cipher;
IV : in Word_Block_Type);
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Encoder is new Cipher and Util.Encoders.Transformer with private;
-- Set the encryption key to use.
procedure Set_Key (E : in out Encoder;
Data : in Secret_Key;
Mode : in AES_Mode := CBC);
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Finish encoding the input array.
overriding
procedure Finish (E : in out Encoder;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset)
with Pre => Into'Length >= Block_Type'Length,
Post => Last = Into'First - 1 or Last = Into'First + Block_Type'Length - 1;
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Decoder is new Cipher and Util.Encoders.Transformer with private;
-- Set the decryption key to use.
procedure Set_Key (E : in out Decoder;
Data : in Secret_Key;
Mode : in AES_Mode := CBC);
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
-- Finish encoding the input array.
overriding
procedure Finish (E : in out Decoder;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset);
private
use Interfaces;
subtype Count_Type is Ada.Streams.Stream_Element_Offset range 0 .. 16;
type Block_Key is array (0 .. 59) of Unsigned_32;
type Key_Type is record
Key : Block_Key := (others => 0);
Rounds : Natural := 0;
end record;
type Cipher is limited new Ada.Finalization.Limited_Controlled with record
IV : Word_Block_Type := (others => 0);
Key : Key_Type;
Mode : AES_Mode := CBC;
Data_Count : Count_Type := 0;
Data : Block_Type;
Data2 : Block_Type;
end record;
overriding
procedure Finalize (Object : in out Cipher);
type Encoder is new Cipher and Util.Encoders.Transformer with null record;
type Decoder is new Cipher and Util.Encoders.Transformer with null record;
end Util.Encoders.AES;
|
Add Count_Type to better detect array indexing issues Add Data2 for some AES modes
|
Add Count_Type to better detect array indexing issues
Add Data2 for some AES modes
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
0d2e706d811dcae74489063a9b348bff07130c20
|
awa/regtests/awa-users-tests.adb
|
awa/regtests/awa-users-tests.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- 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.Tests;
with Util.Test_Caller;
with ASF.Tests;
with AWA.Tests;
with AWA.Users.Models;
with AWA.Users.Services.Tests.Helpers;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
package body AWA.Users.Tests is
use ASF.Tests;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of user by simulating web requests.
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Email : constant String := "Joe-" & Util.Tests.Get_UUID & "@gmail.com";
Principal : Services.Tests.Helpers.Test_User;
begin
Services.Tests.Helpers.Initialize (Principal);
Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("password", "asdf");
Request.Set_Parameter ("password2", "asdf");
Request.Set_Parameter ("firstName", "joe");
Request.Set_Parameter ("lastName", "dalton");
Request.Set_Parameter ("register", "1");
Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
-- Now, get the access key and simulate a click on the validation link.
declare
Key : AWA.Users.Models.Access_Key_Ref;
begin
Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
Request.Set_Parameter ("key", Key.Get_Access_Key);
Do_Get (Request, Reply, "/auth/validate.html", "validate-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
end;
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Create_User;
procedure Test_Logout_User (T : in out Test) is
begin
null;
end Test_Logout_User;
-- ------------------------------
-- Test user authentication by simulating a web request.
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Principal :Services.Tests.Helpers.Test_User;
begin
AWA.Tests.Set_Application_Context;
Services.Tests.Helpers.Create_User (Principal, "[email protected]");
Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("login", "1");
Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Login_User;
-- ------------------------------
-- Test the reset password by simulating web requests.
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Email : constant String := "[email protected]";
begin
Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("lost-password", "1");
Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Now, get the access key and simulate a click on the reset password link.
declare
Principal : Services.Tests.Helpers.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
AWA.Tests.Set_Application_Context;
Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
-- Simulate user clicking on the reset password link.
-- This verifies the key, login the user and redirect him to the change-password page
Request.Set_Parameter ("key", Key.Get_Access_Key);
Do_Get (Request, Reply, "/auth/reset-password.html", "reset-password-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Post the reset password
Request.Set_Parameter ("password", "asd");
Request.Set_Parameter ("reset-password", "1");
Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is logged and we have a user principal now.
t.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end;
end Test_Reset_Password_User;
end AWA.Users.Tests;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- 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.Tests;
with Util.Test_Caller;
with ASF.Tests;
with AWA.Tests;
with AWA.Users.Models;
with AWA.Users.Services.Tests.Helpers;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
package body AWA.Users.Tests is
use ASF.Tests;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of user by simulating web requests.
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Email : constant String := "Joe-" & Util.Tests.Get_UUID & "@gmail.com";
Principal : Services.Tests.Helpers.Test_User;
begin
Services.Tests.Helpers.Initialize (Principal);
Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("password", "asdf");
Request.Set_Parameter ("password2", "asdf");
Request.Set_Parameter ("firstName", "joe");
Request.Set_Parameter ("lastName", "dalton");
Request.Set_Parameter ("register", "1");
Request.Set_Parameter ("register-button", "1");
Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
-- Now, get the access key and simulate a click on the validation link.
declare
Key : AWA.Users.Models.Access_Key_Ref;
begin
Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
Request.Set_Parameter ("key", Key.Get_Access_Key);
Do_Get (Request, Reply, "/auth/validate.html", "validate-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
end;
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Create_User;
procedure Test_Logout_User (T : in out Test) is
begin
null;
end Test_Logout_User;
-- ------------------------------
-- Test user authentication by simulating a web request.
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Principal :Services.Tests.Helpers.Test_User;
begin
AWA.Tests.Set_Application_Context;
Services.Tests.Helpers.Create_User (Principal, "[email protected]");
Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("login", "1");
Request.Set_Parameter ("login-button", "1");
Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Login_User;
-- ------------------------------
-- Test the reset password by simulating web requests.
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Email : constant String := "[email protected]";
begin
Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("lost-password", "1");
Request.Set_Parameter ("lost-password-button", "1");
Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Now, get the access key and simulate a click on the reset password link.
declare
Principal : Services.Tests.Helpers.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
AWA.Tests.Set_Application_Context;
Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
-- Simulate user clicking on the reset password link.
-- This verifies the key, login the user and redirect him to the change-password page
Request.Set_Parameter ("key", Key.Get_Access_Key);
Do_Get (Request, Reply, "/auth/reset-password.html", "reset-password-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Post the reset password
Request.Set_Parameter ("password", "asd");
Request.Set_Parameter ("reset-password", "1");
Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is logged and we have a user principal now.
t.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end;
end Test_Reset_Password_User;
end AWA.Users.Tests;
|
Fix unit test after changes in XHTML files
|
Fix unit test after changes in XHTML files
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
4b09fbf3e772513d7ef397700af434c3763cd361
|
awa/src/awa-components-wikis.ads
|
awa/src/awa-components-wikis.ads
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ASF.Contexts.Faces;
with ASF.Components;
with ASF.Components.Html;
with Wiki.Strings;
with Wiki.Render;
with Wiki.Plugins;
with Wiki.Render.Links;
package AWA.Components.Wikis is
use ASF.Contexts.Faces;
-- The wiki format of the wiki text. The valid values are:
-- dotclear, google, creole, phpbb, mediawiki
FORMAT_NAME : constant String := "format";
VALUE_NAME : constant String := ASF.Components.VALUE_NAME;
-- The link renderer bean that controls the generation of page and image links.
LINKS_NAME : constant String := "links";
-- The plugin factory bean that must be used for Wiki plugins.
PLUGINS_NAME : constant String := "plugins";
-- ------------------------------
-- Wiki component
-- ------------------------------
--
-- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/>
--
type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record;
type UIWiki_Access is access all UIWiki'Class;
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Wiki_Syntax;
-- Get the links renderer that must be used to render image and page links.
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Links.Link_Renderer_Access;
-- Get the plugin factory that must be used by the Wiki parser.
function Get_Plugin_Factory (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Plugins.Plugin_Factory_Access;
-- Render the wiki text
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class);
use Ada.Strings.Wide_Wide_Unbounded;
IMAGE_PREFIX_ATTR : constant String := "image_prefix";
PAGE_PREFIX_ATTR : constant String := "page_prefix";
type Link_Renderer_Bean is new Util.Beans.Basic.Bean
and Wiki.Render.Links.Link_Renderer with record
Page_Prefix : Unbounded_Wide_Wide_String;
Image_Prefix : Unbounded_Wide_Wide_String;
end record;
-- Make a link adding a prefix unless the link is already absolute.
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String);
-- Get the value identified by the name.
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Link_Renderer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
private
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean;
end AWA.Components.Wikis;
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ASF.Contexts.Faces;
with ASF.Components;
with ASF.Components.Html;
with Wiki.Strings;
with Wiki.Render;
with Wiki.Plugins;
with Wiki.Render.Links;
package AWA.Components.Wikis is
use ASF.Contexts.Faces;
-- The wiki format of the wiki text. The valid values are:
-- dotclear, google, creole, phpbb, mediawiki
FORMAT_NAME : constant String := "format";
VALUE_NAME : constant String := ASF.Components.VALUE_NAME;
-- The link renderer bean that controls the generation of page and image links.
LINKS_NAME : constant String := "links";
-- The plugin factory bean that must be used for Wiki plugins.
PLUGINS_NAME : constant String := "plugins";
-- ------------------------------
-- Wiki component
-- ------------------------------
--
-- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/>
--
type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record;
type UIWiki_Access is access all UIWiki'Class;
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Wiki_Syntax;
-- Get the links renderer that must be used to render image and page links.
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Links.Link_Renderer_Access;
-- Get the plugin factory that must be used by the Wiki parser.
function Get_Plugin_Factory (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Plugins.Plugin_Factory_Access;
-- Render the wiki text
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class);
use Ada.Strings.Wide_Wide_Unbounded;
IMAGE_PREFIX_ATTR : constant String := "image_prefix";
PAGE_PREFIX_ATTR : constant String := "page_prefix";
type Link_Renderer_Bean is new Util.Beans.Basic.Bean
and Wiki.Render.Links.Link_Renderer with record
Page_Prefix : Unbounded_Wide_Wide_String;
Image_Prefix : Unbounded_Wide_Wide_String;
end record;
-- Make a link adding a prefix unless the link is already absolute.
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String);
-- Get the value identified by the name.
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Link_Renderer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in out Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in out Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
private
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean;
end AWA.Components.Wikis;
|
Change the link renderer to in out parameter
|
Change the link renderer to in out parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
2fdf5d95a565954561da0d6a403bd84eb291a769
|
awa/plugins/awa-mail/src/awa-mail-clients.ads
|
awa/plugins/awa-mail/src/awa-mail-clients.ads
|
-----------------------------------------------------------------------
-- awa-mail-client -- Mail client interface
-- Copyright (C) 2012, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Properties;
-- The <b>AWA.Mail.Clients</b> package defines a mail client API used by the mail module.
-- It defines two interfaces that must be implemented. This allows to have an implementation
-- based on an external application such as <tt>sendmail</tt> and other implementation that
-- use an SMTP connection.
package AWA.Mail.Clients is
use Ada.Strings.Unbounded;
type Recipient_Type is (TO, CC, BCC);
-- ------------------------------
-- Mail Message
-- ------------------------------
-- The <b>Mail_Message</b> represents an abstract mail message that can be initialized
-- before being sent.
type Mail_Message is limited interface;
type Mail_Message_Access is access all Mail_Message'Class;
-- Set the <tt>From</tt> part of the message.
procedure Set_From (Message : in out Mail_Message;
Name : in String;
Address : in String) is abstract;
-- Add a recipient for the message.
procedure Add_Recipient (Message : in out Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String) is abstract;
-- Set the subject of the message.
procedure Set_Subject (Message : in out Mail_Message;
Subject : in String) is abstract;
-- Set the body of the message.
procedure Set_Body (Message : in out Mail_Message;
Content : in Unbounded_String;
Alternative : in Unbounded_String;
Content_Type : in String := "") is abstract;
-- Add an attachment with the given content.
procedure Add_Attachment (Message : in out Mail_Message;
Content : in Unbounded_String;
Content_Id : in String;
Content_Type : in String) is abstract;
-- Send the email message.
procedure Send (Message : in out Mail_Message) is abstract;
-- ------------------------------
-- Mail Manager
-- ------------------------------
-- The <b>Mail_Manager</b> is the entry point to create a new mail message
-- and be able to send it.
type Mail_Manager is limited interface;
type Mail_Manager_Access is access all Mail_Manager'Class;
-- Create a new mail message.
function Create_Message (Manager : in Mail_Manager) return Mail_Message_Access is abstract;
-- Factory to create the mail manager. The mail manager implementation is identified by
-- the <b>Name</b>. It is configured according to the properties defined in <b>Props</b>.
-- Returns null if the mail manager identified by the name is not supported.
function Factory (Name : in String;
Props : in Util.Properties.Manager'Class)
return Mail_Manager_Access;
end AWA.Mail.Clients;
|
-----------------------------------------------------------------------
-- awa-mail-client -- Mail client interface
-- Copyright (C) 2012, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Properties;
-- The <b>AWA.Mail.Clients</b> package defines a mail client API used by the mail module.
-- It defines two interfaces that must be implemented. This allows to have an implementation
-- based on an external application such as <tt>sendmail</tt> and other implementation that
-- use an SMTP connection.
package AWA.Mail.Clients is
use Ada.Strings.Unbounded;
type Recipient_Type is (TO, CC, BCC);
-- ------------------------------
-- Mail Message
-- ------------------------------
-- The <b>Mail_Message</b> represents an abstract mail message that can be initialized
-- before being sent.
type Mail_Message is limited interface;
type Mail_Message_Access is access all Mail_Message'Class;
-- Set the <tt>From</tt> part of the message.
procedure Set_From (Message : in out Mail_Message;
Name : in String;
Address : in String) is abstract;
-- Add a recipient for the message.
procedure Add_Recipient (Message : in out Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String) is abstract;
-- Set the subject of the message.
procedure Set_Subject (Message : in out Mail_Message;
Subject : in String) is abstract;
-- Set the body of the message.
procedure Set_Body (Message : in out Mail_Message;
Content : in Unbounded_String;
Alternative : in Unbounded_String;
Content_Type : in String := "") is abstract;
-- Add an attachment with the given content.
procedure Add_Attachment (Message : in out Mail_Message;
Content : in Unbounded_String;
Content_Id : in String;
Content_Type : in String) is abstract;
-- Add a file attachment.
procedure Add_File_Attachment (Message : in out Mail_Message;
Filename : in String;
Content_Id : in String;
Content_Type : in String) is abstract;
-- Send the email message.
procedure Send (Message : in out Mail_Message) is abstract;
-- ------------------------------
-- Mail Manager
-- ------------------------------
-- The <b>Mail_Manager</b> is the entry point to create a new mail message
-- and be able to send it.
type Mail_Manager is limited interface;
type Mail_Manager_Access is access all Mail_Manager'Class;
-- Create a new mail message.
function Create_Message (Manager : in Mail_Manager) return Mail_Message_Access is abstract;
-- Factory to create the mail manager. The mail manager implementation is identified by
-- the <b>Name</b>. It is configured according to the properties defined in <b>Props</b>.
-- Returns null if the mail manager identified by the name is not supported.
function Factory (Name : in String;
Props : in Util.Properties.Manager'Class)
return Mail_Manager_Access;
end AWA.Mail.Clients;
|
Declare the Add_File_Attachment procedure
|
Declare the Add_File_Attachment procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
be82876daf5bf7fc524ed4732bd1808b09738021
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 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 ASF.Applications;
with ADO;
with AWA.Modules;
with AWA.Blogs.Models;
with AWA.Counters.Definition;
with Security.Permissions;
-- == Integration ==
-- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application.
-- It provides operations that are used by the blog beans or other services to create and update
-- posts. An instance of the <tt>Blog_Module</tt> must be declared and registered in the
-- AWA application. The module instance can be defined as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Blogs.Modules.NAME,
-- URI => "blogs",
-- Module => App.Blog_Module'Access);
--
package AWA.Blogs.Modules is
NAME : constant String := "blogs";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
-- Define the read post counter.
package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count");
Not_Found : exception;
type Blog_Module is new AWA.Modules.Module with private;
type Blog_Module_Access is access all Blog_Module'Class;
-- Initialize the blog module.
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the blog module instance associated with the current application.
function Get_Blog_Module return Blog_Module_Access;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
private
type Blog_Module is new AWA.Modules.Module with null record;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 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 ASF.Applications;
with ADO;
with Wiki.Strings;
with AWA.Modules;
with AWA.Blogs.Models;
with AWA.Counters.Definition;
with Security.Permissions;
-- == Integration ==
-- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application.
-- It provides operations that are used by the blog beans or other services to create and update
-- posts. An instance of the <tt>Blog_Module</tt> must be declared and registered in the
-- AWA application. The module instance can be defined as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Blogs.Modules.NAME,
-- URI => "blogs",
-- Module => App.Blog_Module'Access);
--
package AWA.Blogs.Modules is
NAME : constant String := "blogs";
-- The configuration parameter that defines the image link prefix in rendered HTML content.
PARAM_IMAGE_PREFIX : constant String := "image_prefix";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
-- Define the read post counter.
package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count");
Not_Found : exception;
type Blog_Module is new AWA.Modules.Module with private;
type Blog_Module_Access is access all Blog_Module'Class;
-- Initialize the blog module.
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Blog_Module;
Props : in ASF.Applications.Config);
-- Get the blog module instance associated with the current application.
function Get_Blog_Module return Blog_Module_Access;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
private
type Blog_Module is new AWA.Modules.Module with record
Image_Prefix : Wiki.Strings.UString;
end record;
end AWA.Blogs.Modules;
|
Declare PARAM_IMAGE_PREFIX constant and override the Configure procedure
|
Declare PARAM_IMAGE_PREFIX constant and override the Configure procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
d20b93f34510316f076175f2ad1ed8eb36fdfbdb
|
src/asf-components-widgets-inputs.adb
|
src/asf-components-widgets-inputs.adb
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input widget components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Conversions;
with ASF.Models.Selects;
with ASF.Components.Base;
with ASF.Components.Utils;
with ASF.Components.Html.Messages;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Vectors;
with Util.Strings.Transforms;
with Util.Beans.Objects;
package body ASF.Components.Widgets.Inputs is
-- ------------------------------
-- Render the input field title.
-- ------------------------------
procedure Render_Title (UI : in UIInput;
Name : in String;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class) is
Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title");
begin
Writer.Start_Element ("dt");
Writer.Start_Element ("label");
Writer.Write_Attribute ("for", Name);
Writer.Write_Text (Title);
Writer.End_Element ("label");
Writer.End_Element ("dt");
end Render_Title;
-- ------------------------------
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
Style : constant String := UI.Get_Attribute ("styleClass", Context);
begin
Writer.Start_Element ("dl");
Writer.Write_Attribute ("id", Id);
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Writer.Write_Attribute ("class", Style & " asf-error");
elsif Style'Length > 0 then
Writer.Write_Attribute ("class", Style);
end if;
UI.Render_Title (Id, Writer, Context);
Writer.Start_Element ("dd");
UI.Render_Input (Context, Write_Id => False);
end;
end Encode_Begin;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the error message associated with the input field.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages),
SPAN_NO_STYLE, False, True, Context);
end if;
Writer.End_Element ("dd");
Writer.End_Element ("dl");
end;
end Encode_End;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the autocomplete script and finish the input component.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Queue_Script ("$('#");
Writer.Queue_Script (Id);
Writer.Queue_Script (" input').complete({");
Writer.Queue_Script ("});");
UIInput (UI).Encode_End (Context);
end;
end Encode_End;
overriding
procedure Process_Decodes (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Val : constant String := Context.Get_Parameter (Id & ".match");
begin
if Val'Length > 0 then
UI.Match_Value := Util.Beans.Objects.To_Object (Val);
else
ASF.Components.Html.Forms.UIInput (UI).Process_Decodes (Context);
end if;
end;
end Process_Decodes;
procedure Render_List (UI : in UIComplete;
Match : in String;
Context : in out Faces_Context'Class) is
use type Util.Beans.Basic.List_Bean_Access;
List : constant Util.Beans.Basic.List_Bean_Access
:= ASF.Components.Utils.Get_List_Bean (UI, "autocomplete", Context);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Need_Comma : Boolean := False;
Count : Natural;
procedure Render_Item (Label : in String) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
if Match'Length = 0 or else
(Match'Length <= Label'Length
and then Match = Label (Label'First .. Label'First + Match'Length - 1)) then
if Need_Comma then
Writer.Write (",");
end if;
Writer.Write ('"');
Util.Strings.Transforms.Escape_Java (Content => Label,
Into => Result);
Writer.Write (Result);
Writer.Write ('"');
Need_Comma := True;
end if;
end Render_Item;
begin
Writer.Write ('[');
if List /= null then
Count := List.Get_Count;
if List.all in ASF.Models.Selects.Select_Item_List'Class then
declare
S : access ASF.Models.Selects.Select_Item_List'Class
:= ASF.Models.Selects.Select_Item_List'Class (List.all)'Access;
begin
for I in 1 .. Count loop
Render_Item (Ada.Characters.Conversions.To_String (S.Get_Select_Item (I).Get_Label));
end loop;
end;
else
for I in 1 .. Count loop
List.Set_Row_Index (I);
declare
Value : constant Util.Beans.Objects.Object := List.Get_Row;
Label : constant String := Util.Beans.Objects.To_String (Value);
begin
Render_Item (Label);
end;
end loop;
end if;
end if;
Writer.Write (']');
end Render_List;
overriding
procedure Process_Updates (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not Util.Beans.Objects.Is_Empty (UI.Match_Value) then
declare
Value : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("match");
ME : EL.Expressions.Method_Expression;
begin
if Value /= null then
declare
VE : constant EL.Expressions.Value_Expression
:= ASF.Views.Nodes.Get_Value_Expression (Value.all);
begin
VE.Set_Value (Value => UI.Match_Value, Context => Context.Get_ELContext.all);
end;
end if;
-- Post an event on this component to trigger the rendering of the completion
-- list as part of an application/json output. The rendering is made by Broadcast.
ASF.Events.Faces.Actions.Post_Event (UI => UI,
Method => ME);
end;
else
ASF.Components.Html.Forms.UIInput (UI).Process_Updates (Context);
end if;
-- exception
-- when E : others =>
-- UI.Is_Valid := False;
-- UI.Add_Message (CONVERTER_MESSAGE_NAME, "convert", Context);
-- Log.Info (Utils.Get_Line_Info (UI)
-- & ": Exception raised when updating value {0} for component {1}: {2}",
-- EL.Objects.To_String (UI.Submitted_Value),
-- To_String (UI.Get_Client_Id), Ada.Exceptions.Exception_Name (E));
end Process_Updates;
-- ------------------------------
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
-- ------------------------------
overriding
procedure Broadcast (UI : in out UIComplete;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out Faces_Context'Class) is
pragma Unreferenced (Event);
Match : constant String := Util.Beans.Objects.To_String (UI.Match_Value);
begin
Context.Get_Response.Set_Content_Type ("application/json; charset=UTF-8");
UI.Render_List (Match, Context);
Context.Response_Completed;
end Broadcast;
end ASF.Components.Widgets.Inputs;
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input widget components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Conversions;
with ASF.Models.Selects;
with ASF.Components.Base;
with ASF.Components.Utils;
with ASF.Components.Html.Messages;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Vectors;
with Util.Strings.Transforms;
with Util.Beans.Objects;
package body ASF.Components.Widgets.Inputs is
-- ------------------------------
-- Render the input field title.
-- ------------------------------
procedure Render_Title (UI : in UIInput;
Name : in String;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class) is
Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title");
begin
Writer.Start_Element ("dt");
Writer.Start_Element ("label");
Writer.Write_Attribute ("for", Name);
Writer.Write_Text (Title);
Writer.End_Element ("label");
Writer.End_Element ("dt");
end Render_Title;
-- ------------------------------
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
Style : constant String := UI.Get_Attribute ("styleClass", Context);
begin
Writer.Start_Element ("dl");
Writer.Write_Attribute ("id", Id);
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Writer.Write_Attribute ("class", Style & " asf-error");
elsif Style'Length > 0 then
Writer.Write_Attribute ("class", Style);
end if;
UI.Render_Title (Id, Writer, Context);
Writer.Start_Element ("dd");
UI.Render_Input (Context, Write_Id => False);
end;
end Encode_Begin;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the error message associated with the input field.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages),
SPAN_NO_STYLE, False, True, Context);
end if;
Writer.End_Element ("dd");
Writer.End_Element ("dl");
end;
end Encode_End;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the autocomplete script and finish the input component.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Queue_Script ("$('#");
Writer.Queue_Script (Id);
Writer.Queue_Script (" input').complete({");
Writer.Queue_Script ("});");
UIInput (UI).Encode_End (Context);
end;
end Encode_End;
overriding
procedure Process_Decodes (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Val : constant String := Context.Get_Parameter (Id & ".match");
begin
if Val'Length > 0 then
UI.Match_Value := Util.Beans.Objects.To_Object (Val);
else
ASF.Components.Html.Forms.UIInput (UI).Process_Decodes (Context);
end if;
end;
end Process_Decodes;
procedure Render_List (UI : in UIComplete;
Match : in String;
Context : in out Faces_Context'Class) is
use type Util.Beans.Basic.List_Bean_Access;
List : constant Util.Beans.Basic.List_Bean_Access
:= ASF.Components.Utils.Get_List_Bean (UI, "autocompleteList", Context);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Need_Comma : Boolean := False;
Count : Natural;
procedure Render_Item (Label : in String) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
if Match'Length = 0 or else
(Match'Length <= Label'Length
and then Match = Label (Label'First .. Label'First + Match'Length - 1)) then
if Need_Comma then
Writer.Write (",");
end if;
Writer.Write ('"');
Util.Strings.Transforms.Escape_Java (Content => Label,
Into => Result);
Writer.Write (Result);
Writer.Write ('"');
Need_Comma := True;
end if;
end Render_Item;
begin
Writer.Write ('[');
if List /= null then
Count := List.Get_Count;
if List.all in ASF.Models.Selects.Select_Item_List'Class then
declare
S : constant access ASF.Models.Selects.Select_Item_List'Class
:= ASF.Models.Selects.Select_Item_List'Class (List.all)'Access;
begin
for I in 1 .. Count loop
Render_Item (Ada.Characters.Conversions.To_String (S.Get_Select_Item (I).Get_Label));
end loop;
end;
else
for I in 1 .. Count loop
List.Set_Row_Index (I);
declare
Value : constant Util.Beans.Objects.Object := List.Get_Row;
Label : constant String := Util.Beans.Objects.To_String (Value);
begin
Render_Item (Label);
end;
end loop;
end if;
end if;
Writer.Write (']');
end Render_List;
overriding
procedure Process_Updates (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not Util.Beans.Objects.Is_Empty (UI.Match_Value) then
declare
Value : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("match");
ME : EL.Expressions.Method_Expression;
begin
if Value /= null then
declare
VE : constant EL.Expressions.Value_Expression
:= ASF.Views.Nodes.Get_Value_Expression (Value.all);
begin
VE.Set_Value (Value => UI.Match_Value, Context => Context.Get_ELContext.all);
end;
end if;
-- Post an event on this component to trigger the rendering of the completion
-- list as part of an application/json output. The rendering is made by Broadcast.
ASF.Events.Faces.Actions.Post_Event (UI => UI,
Method => ME);
end;
else
ASF.Components.Html.Forms.UIInput (UI).Process_Updates (Context);
end if;
-- exception
-- when E : others =>
-- UI.Is_Valid := False;
-- UI.Add_Message (CONVERTER_MESSAGE_NAME, "convert", Context);
-- Log.Info (Utils.Get_Line_Info (UI)
-- & ": Exception raised when updating value {0} for component {1}: {2}",
-- EL.Objects.To_String (UI.Submitted_Value),
-- To_String (UI.Get_Client_Id), Ada.Exceptions.Exception_Name (E));
end Process_Updates;
-- ------------------------------
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
-- ------------------------------
overriding
procedure Broadcast (UI : in out UIComplete;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out Faces_Context'Class) is
pragma Unreferenced (Event);
Match : constant String := Util.Beans.Objects.To_String (UI.Match_Value);
begin
Context.Get_Response.Set_Content_Type ("application/json; charset=UTF-8");
UI.Render_List (Match, Context);
Context.Response_Completed;
end Broadcast;
end ASF.Components.Widgets.Inputs;
|
Use the attribute 'autocompleteList' to define the list of autocompletion
|
Use the attribute 'autocompleteList' to define the list of autocompletion
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
89f08493a6a4e15380251ea967054f3099845ff9
|
matp/src/frames/mat-frames.ads
|
matp/src/frames/mat-frames.ads
|
-----------------------------------------------------------------------
-- mat-frames - Representation of stack frames
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
with MAT.Events;
package MAT.Frames is
Not_Found : exception;
type Frame_Type is private;
subtype Frame_Table is MAT.Events.Frame_Table;
-- Return the parent frame.
function Parent (Frame : in Frame_Type) return Frame_Type;
-- Returns the backtrace of the current frame (up to the root).
-- When <tt>Max_Level</tt> is positive, limit the number of PC frames to the value.
function Backtrace (Frame : in Frame_Type;
Max_Level : in Natural := 0) return Frame_Table;
-- Returns all the direct calls made by the current frame.
function Calls (Frame : in Frame_Type) return Frame_Table;
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
function Count_Children (Frame : in Frame_Type;
Recursive : in Boolean := False) return Natural;
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
function Current_Depth (Frame : in Frame_Type) return Natural;
-- Create a root for stack frame representation.
function Create_Root return Frame_Type;
-- Destroy the frame tree recursively.
procedure Destroy (Frame : in out Frame_Type);
-- Release the frame when its reference is no longer necessary.
procedure Release (Frame : in Frame_Type);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Insert (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type);
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (Frame : in Frame_Type;
Pc : in MAT.Types.Target_Addr) return Frame_Type;
function Find (Frame : in Frame_Type;
Pc : in Frame_Table) return Frame_Type;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
procedure Find (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type;
Last_Pc : out Natural);
-- Check whether the frame contains a call to the function described by the address range.
function In_Function (Frame : in Frame_Type;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr) return Boolean;
private
Frame_Group_Size : constant Natural := 4;
subtype Local_Depth_Type is Natural range 0 .. Frame_Group_Size;
subtype Mini_Frame_Table is Frame_Table (1 .. Local_Depth_Type'Last);
type Frame;
type Frame_Type is access all Frame;
type Frame is record
Parent : Frame_Type := null;
Next : Frame_Type := null;
Children : Frame_Type := null;
Used : Natural := 0;
Depth : Natural := 0;
Calls : Mini_Frame_Table;
Local_Depth : Local_Depth_Type := 0;
end record;
end MAT.Frames;
|
-----------------------------------------------------------------------
-- mat-frames - Representation of stack frames
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
with MAT.Events;
package MAT.Frames is
Not_Found : exception;
type Frame_Type is private;
subtype Frame_Table is MAT.Events.Frame_Table;
-- Return the parent frame.
function Parent (Frame : in Frame_Type) return Frame_Type;
-- Returns the backtrace of the current frame (up to the root).
-- When <tt>Max_Level</tt> is positive, limit the number of PC frames to the value.
function Backtrace (Frame : in Frame_Type;
Max_Level : in Natural := 0) return Frame_Table;
-- Returns all the direct calls made by the current frame.
function Calls (Frame : in Frame_Type) return Frame_Table;
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
function Count_Children (Frame : in Frame_Type;
Recursive : in Boolean := False) return Natural;
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
function Current_Depth (Frame : in Frame_Type) return Natural;
-- Create a root for stack frame representation.
function Create_Root return Frame_Type;
-- Destroy the frame tree recursively.
procedure Destroy (Frame : in out Frame_Type);
-- Release the frame when its reference is no longer necessary.
procedure Release (Frame : in Frame_Type);
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
procedure Insert (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type);
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (Frame : in Frame_Type;
Pc : in MAT.Types.Target_Addr) return Frame_Type;
function Find (Frame : in Frame_Type;
Pc : in Frame_Table) return Frame_Type;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
procedure Find (Frame : in Frame_Type;
Pc : in Frame_Table;
Result : out Frame_Type;
Last_Pc : out Natural);
-- Check whether the frame contains a call to the function described by the address range.
function In_Function (Frame : in Frame_Type;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr) return Boolean;
-- Check whether the inner most frame contains a call to the function described by
-- the address range. This function looks only at the inner most frame and not the
-- whole stack frame.
function By_Function (Frame : in Frame_Type;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr) return Boolean;
private
Frame_Group_Size : constant Natural := 4;
subtype Local_Depth_Type is Natural range 0 .. Frame_Group_Size;
subtype Mini_Frame_Table is Frame_Table (1 .. Local_Depth_Type'Last);
type Frame;
type Frame_Type is access all Frame;
type Frame is record
Parent : Frame_Type := null;
Next : Frame_Type := null;
Children : Frame_Type := null;
Used : Natural := 0;
Depth : Natural := 0;
Calls : Mini_Frame_Table;
Local_Depth : Local_Depth_Type := 0;
end record;
end MAT.Frames;
|
Declare the By_Function function
|
Declare the By_Function function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
02730cb5971d7607304030314ba43c8bb5123241
|
mat/src/gtk/mat-callbacks.ads
|
mat/src/gtk/mat-callbacks.ads
|
-----------------------------------------------------------------------
-- mat-callbacks - Callbacks for Gtk
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Types;
with Gtkada.Builder;
package MAT.Callbacks is
-- Initialize and register the callbacks.
procedure Initialize (Builder : in Gtkada.Builder.Gtkada_Builder);
-- Callback executed when the "quit" action is executed from the menu.
procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "about" action is executed from the menu.
procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "close-about" action is executed from the about box.
procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
end MAT.Callbacks;
|
-----------------------------------------------------------------------
-- mat-callbacks - Callbacks for Gtk
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Gtkada.Builder;
with MAT.Targets.Gtkmat;
package MAT.Callbacks is
-- Initialize and register the callbacks.
procedure Initialize (Target : in MAT.Targets.Gtkmat.Target_Type_Access;
Builder : in Gtkada.Builder.Gtkada_Builder);
-- Callback executed when the "quit" action is executed from the menu.
procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "about" action is executed from the menu.
procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "close-about" action is executed from the about box.
procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
end MAT.Callbacks;
|
Add the Target_Type_Access parameter to the Initialize procedure
|
Add the Target_Type_Access parameter to the Initialize procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
7ca7a178ef0aeebb73d4c5b30f79a477a1112fa9
|
src/gen-commands-layout.adb
|
src/gen-commands-layout.adb
|
-----------------------------------------------------------------------
-- gen-commands-layout -- Layout creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Gen.Artifacts;
with Util.Strings;
with Util.Files;
package body Gen.Commands.Layout is
-- ------------------------------
-- 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 (Name);
use Ada.Strings.Unbounded;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory;
Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts");
function Get_Name return String is
Name : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else "");
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
Page_Name : constant String := Get_Name;
begin
if Page_Name'Length = 0 then
Cmd.Usage (Name);
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Layout_Dir);
Generator.Set_Global ("pageName", Page_Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("add-layout: Add a new layout page to the application");
Put_Line ("Usage: add-layout NAME");
New_Line;
Put_Line (" The layout page allows to give a common look to a set of pages.");
Put_Line (" You can create several layouts for your application.");
Put_Line (" Each layout can reference one or several building blocks that are defined");
Put_Line (" in the original page.");
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/WEB-INF/layouts/<name>.xhtml");
end Help;
end Gen.Commands.Layout;
|
-----------------------------------------------------------------------
-- gen-commands-layout -- Layout creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Gen.Artifacts;
with Util.Strings;
with Util.Files;
package body Gen.Commands.Layout is
-- ------------------------------
-- 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
use Ada.Strings.Unbounded;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory;
Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts");
function Get_Name return String is
Name : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else "");
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
Page_Name : constant String := Get_Name;
begin
if Page_Name'Length = 0 then
Cmd.Usage (Name);
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Layout_Dir);
Generator.Set_Global ("pageName", Page_Name);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("add-layout: Add a new layout page to the application");
Put_Line ("Usage: add-layout NAME");
New_Line;
Put_Line (" The layout page allows to give a common look to a set of pages.");
Put_Line (" You can create several layouts for your application.");
Put_Line (" Each layout can reference one or several building blocks that are defined");
Put_Line (" in the original page.");
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/WEB-INF/layouts/<name>.xhtml");
end Help;
end Gen.Commands.Layout;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
22bcafff3de2704aa824ced3f4bd48f820954509
|
single-substitution-cipher/ada/src/Decipherer.adb
|
single-substitution-cipher/ada/src/Decipherer.adb
|
with Ada.Containers.Ordered_Sets;
with Ada.Unchecked_Deallocation;
with Ada.Text_IO;
package body Decipherer is
package Character_Sets is new Ada.Containers.Ordered_Sets(Element_Type => Encrypted_Char);
package IO renames Ada.Text_IO;
type Mapping_Candidates is Array(Positive range 1 .. 26) of Character;
type Char_Possibilities is record
c : Encrypted_Char;
num_possible : Natural;
possibilities : Mapping_Candidates;
end record;
type Word_Possibilities is record
is_using_root : Boolean;
words : Word_List.Word_Vector;
end record;
type Char_Possibilities_Array is Array(Positive range <>) of Char_Possibilities;
type Word_Possibilities_Array is Array(Positive range <>) of Word_Possibilities;
type Word_Inclusion is Array(Positive range <>, Positive range <>) of Natural;
type Letter_Toggle is Array(Positive range <>) of Boolean;
type Word_Toggle is Array(Positive range <>) of Boolean;
package Word_Vectors renames Word_List.Word_Vectors;
function "="(a, b: Word_Vectors.Cursor) return Boolean renames Word_Vectors."=";
procedure Free_Word_Vector is new Ada.Unchecked_Deallocation(Object => Word_Vectors.Vector, Name => Word_List.Word_Vector);
type Decipher_State (num_words : Positive; num_letters : Positive) is record
candidates : Candidate_Set(1 .. num_words);
characters : Char_Possibilities_Array(1 .. num_letters);
words : Word_Possibilities_Array(1 .. num_words);
inclusion : Word_Inclusion(1 .. num_letters, 1 .. num_words);
end record;
function Image(ew: Encrypted_Word) return Word_List.Word is
w : Word_List.Word;
begin
for i in ew'Range loop
w(i) := Character(ew(i));
end loop;
return w;
end Image;
function Get_Character_Index(state : Decipher_State; c : Encrypted_Char) return Positive is
begin
for ci in state.characters'Range loop
if c = state.characters(ci).c then
return ci;
end if;
end loop;
raise Constraint_Error;
end Get_Character_Index;
function Is_Word_Valid(state : Decipher_State; candidate : Encrypted_Word; word : Word_List.Word) return Boolean is
begin
for i in candidate'Range loop
exit when candidate(i) = ' ';
declare
ci : constant Positive := Get_Character_Index(state, candidate(i));
c : constant Character := word(i);
cp : Char_Possibilities renames state.characters(ci);
found : Boolean := False;
begin
if cp.num_possible = 1 then
found := cp.possibilities(1) = c;
elsif cp.num_possible = 26 then
found := True;
else
for j in 1 .. cp.num_possible loop
if cp.possibilities(j) = c then
found := True;
exit;
end if;
end loop;
end if;
if not found then
return False;
end if;
end;
end loop;
return True;
end Is_Word_Valid;
procedure Filter_Word_List(state : Decipher_State; candidate : Encrypted_Word; initial : Word_List.Word_Vector; final : Word_List.Word_Vector) is
cur : Word_Vectors.Cursor := initial.First;
begin
while cur /= Word_Vectors.No_Element loop
if Is_Word_Valid(state, candidate, Word_Vectors.Element(cur)) then
final.Append(Word_Vectors.Element(cur));
end if;
cur := Word_Vectors.Next(cur);
end loop;
end Filter_Word_List;
procedure Put_Possible(cp: Char_Possibilities) is
begin
for i in 1 .. cp.Num_Possible loop
IO.Put(cp.possibilities(i));
end loop;
IO.New_Line;
end Put_Possible;
procedure Put_Inclusion(state: Decipher_State) is
begin
for i in 1 .. state.Num_Letters loop
IO.Put(Encrypted_Char'Image(state.characters(i).c) & ": ");
for j in 1 .. state.Num_Words loop
exit when state.inclusion(i, j) = 0;
IO.Put(Natural'Image(state.inclusion(i, j)));
end loop;
IO.New_Line;
end loop;
end Put_Inclusion;
procedure Make_Unique(state : in out Decipher_State; ci : Positive; success : out Boolean; changed : in out Letter_Toggle) is
letter : constant Character := state.characters(ci).possibilities(1);
begin
success := True;
-- IO.Put_Line("Determined that " & Encrypted_Char'Image(state.characters(ci).c) & " has to be a " & Character'Image(letter));
for i in state.characters'Range loop
if i /= ci then
declare
cp : Char_Possibilities renames state.characters(i);
begin
for j in 1 .. cp.num_possible loop
if cp.possibilities(j) = letter then
if cp.num_possible = 1 then
success := False;
return;
else
-- IO.Put("Before: "); Put_Possible(cp);
cp.possibilities(j .. cp.num_possible - 1) := cp.possibilities(j + 1 .. cp.num_possible);
cp.num_possible := cp.num_possible - 1;
-- IO.Put("After: "); Put_Possible(cp);
changed(i) := True;
if cp.num_possible = 1 then
-- IO.Put_Line("Make_Unique from Make_Unique");
Make_Unique(state, i, success, changed);
if not success then
return;
end if;
end if;
exit;
end if;
end if;
end loop;
end;
end if;
end loop;
end Make_Unique;
procedure Constrain_Letters(state : in out Decipher_State; wi : Positive; success : out Boolean; changed : in out Letter_Toggle) is
ci : Positive;
cur : Word_Vectors.Cursor := state.words(wi).words.all.First;
word : Word_List.Word;
seen : Array(Positive range 1 .. state.num_letters, Character range 'a' .. 'z') of Boolean := (others => (others => False));
used : Array(Positive range 1 .. state.num_letters) of Boolean := (others => False);
begin
success := True;
while cur /= Word_Vectors.No_Element loop
word := Word_Vectors.Element(cur);
for i in word'Range loop
exit when word(i) = ' ';
ci := Get_Character_Index(state, state.candidates(wi)(i));
seen(ci, word(i)) := True;
used(ci) := True;
end loop;
cur := Word_Vectors.Next(cur);
end loop;
for i in used'range loop
if used(i) then
-- IO.Put("Seen: ");
-- for c in Character range 'a' .. 'z' loop
-- if (seen(i, c)) then
-- IO.Put(c);
-- end if;
-- end loop;
-- IO.New_Line;
declare
cp : Char_Possibilities renames state.characters(i);
shrunk : Boolean := False;
write_head : Natural := 0;
begin
-- IO.Put("Before: "); Put_Possible(cp);
for read_head in 1 .. cp.Num_Possible loop
if seen(i, cp.possibilities(read_head)) then
write_head := write_head + 1;
if write_head /= read_head then
cp.possibilities(write_head) := cp.possibilities(read_head);
end if;
else
shrunk := True;
end if;
end loop;
cp.Num_Possible := write_head;
-- IO.Put("After: "); Put_Possible(cp);
if Shrunk then
changed(i) := True;
if cp.Num_Possible = 0 then
success := False;
return;
elsif cp.Num_Possible = 1 then
-- IO.Put_Line("Make_Unique from Constrain_Letters");
Make_Unique(state, i, success, changed);
if not success then
return;
end if;
end if;
end if;
end;
end if;
end loop;
end Constrain_Letters;
procedure Check_Constraints(state : in out Decipher_State; changed : Letter_Toggle; success : out Boolean) is
words : Word_Toggle(1 .. state.num_words) := (others => False);
follow_up : Letter_Toggle(1 .. state.num_letters) := (others => False);
any_changed : Boolean := False;
begin
success := True;
for i in 1 .. state.num_letters loop
if changed(i) then
any_changed := True;
for j in 1 .. state.num_words loop
exit when state.inclusion(i, j) = 0;
words(state.inclusion(i, j)) := True;
end loop;
end if;
end loop;
if not any_changed then
return;
end if;
for i in 1 .. state.num_words loop
if words(i) then
declare
new_words : Word_List.Word_Vector := new Word_Vectors.Vector;
begin
Filter_Word_List(state, state.candidates(i), state.words(i).words, new_words);
if Natural(new_words.Length) = 0 then
Free_Word_Vector(new_words);
success := False;
return;
elsif Natural(new_words.Length) = Natural(state.words(i).words.Length) then
-- IO.Put_Line("Word set for " & Positive'Image(i) & "(" & Image(state.candidates(i)) & ") did not shrink from " & Ada.Containers.Count_Type'Image(state.words(i).words.all.Length));
Free_Word_Vector(new_Words);
else
-- IO.Put_Line("Restricting word set for " & Positive'Image(i) & "(" & Image(state.candidates(i)) & ") from " & Ada.Containers.Count_Type'Image(state.words(i).words.all.Length) & " to " & Ada.Containers.Count_Type'Image(new_words.all.Length));
if state.words(i).is_using_root then
state.words(i).is_using_root := False;
else
Free_Word_Vector(state.words(i).words);
end if;
state.words(i).words := new_words;
Constrain_Letters(state, i, success, follow_up);
if not success then
return;
end if;
end if;
end;
end if;
end loop;
Check_Constraints(state, follow_up, success);
end Check_Constraints;
procedure Guess_Letter(state : in out Decipher_State; ci : Positive) is
begin
if ci > state.num_letters then
IO.Put_Line("Found Solution");
for ci in 1 .. state.num_letters loop
IO.Put(Character(state.characters(ci).c));
if state.characters(ci).num_possible /= 1 then
IO.Put_Line(": Invalid State");
return;
end if;
end loop;
IO.New_Line;
for ci in 1 .. state.num_letters loop
IO.Put(state.characters(ci).possibilities(1));
end loop;
IO.New_Line;
for wi in 1 .. state.num_words loop
IO.Put(Image(state.candidates(wi)) & ": ");
if Natural(state.words(wi).words.all.Length) = 1 then
IO.Put_Line(state.words(wi).words.all(1));
else
IO.Put_Line("*Invalid: " & Ada.Containers.Count_Type'Image(state.words(wi).words.all.Length) & " Words");
end if;
end loop;
IO.Put_Line("--------------------------");
elsif state.characters(ci).num_possible = 1 then
-- Nothing to do, pass it up the line
Guess_Letter(state, ci + 1);
else
declare
success : Boolean;
changed : Letter_Toggle(1 .. state.num_letters);
characters : constant Char_Possibilities_Array := state.characters;
words : constant Word_Possibilities_Array := state.words;
cp : Char_Possibilities renames characters(ci);
begin
for mi in 1 .. cp.num_possible loop
changed := (others => False);
changed(ci) := True;
state.characters(ci).possibilities(1) := characters(ci).possibilities(mi);
-- IO.Put_Line("Guessing " & Character'Image(state.characters(ci).possibilities(mi)) & " for " & Encrypted_Char'Image(state.characters(ci).c));
state.characters(ci).num_possible := 1;
for wi in 1 .. state.num_words loop
state.words(wi).is_using_root := True;
end loop;
-- IO.Put_Line("Make_Unique from Guess_Letter");
Make_Unique(state, ci, success, changed);
if success then
Check_Constraints(state, changed, success);
if success then
Guess_Letter(state, ci + 1);
end if;
end if;
-- IO.Put_Line("Restore Letter guess for " & Positive'Image(ci));
state.characters := characters;
state.words := words;
end loop;
end;
end if;
end Guess_Letter;
function Decipher(candidates: Candidate_Set; words: Word_List.Word_List) return Result_Set is
letters : Character_Sets.Set;
begin
for ci in candidates'Range loop
for i in candidates(ci)'Range loop
exit when candidates(ci)(i) = ' ';
letters.Include(candidates(ci)(i));
end loop;
end loop;
declare
num_words : constant Positive := Positive(candidates'Length);
num_letters : constant Positive := Positive(letters.Length);
result : Result_Set(1 .. num_letters);
state : Decipher_State(num_words, num_letters);
cur : Character_Sets.Cursor := letters.First;
begin
state.candidates := candidates;
state.inclusion := (others => (others => 0));
for i in 1 .. num_letters loop
state.characters(i).c := Character_Sets.Element(cur);
state.characters(i).num_possible := 26;
for l in Character range 'a' .. 'z' loop
state.characters(i).possibilities(Character'Pos(l) - Character'Pos('a') + 1) := l;
end loop;
cur := Character_Sets.Next(cur);
end loop;
for i in 1 .. num_words loop
for l in candidates(Candidates'First + i - 1)'Range loop
declare
c : constant Encrypted_Char := candidates(Candidates'First + i - 1)(l);
ci : Positive;
begin
exit when c = ' ';
ci := Get_Character_Index(state, c);
for mi in 1 .. num_words loop
if state.inclusion(ci, mi) = 0 then
state.inclusion(ci, mi) := i;
exit;
elsif state.inclusion(ci, mi) = i then
exit;
end if;
end loop;
end;
end loop;
state.words(i).is_using_root := True;
state.words(i).words := words.Element(Word_List.Make_Pattern(Image(candidates(i))));
end loop;
-- Put_Inclusion(state);
Guess_Letter(state, 1);
return result;
end;
end Decipher;
end Decipherer;
|
with Ada.Containers.Ordered_Sets;
with Ada.Unchecked_Deallocation;
with Ada.Containers.Generic_Array_Sort;
with Ada.Text_IO;
package body Decipherer is
package Character_Sets is new Ada.Containers.Ordered_Sets(Element_Type => Encrypted_Char);
package IO renames Ada.Text_IO;
type Priority_Pair is record
item, priority : Integer;
end record;
type Priority_Pair_Array is Array(Positive range <>) of Priority_Pair;
function "<"(a, b : Priority_Pair) return Boolean is
begin
return a.priority > b.priority;
end "<";
procedure Priority_Pair_Sort is new Ada.Containers.Generic_Array_Sort(Index_Type => Positive, Element_Type => Priority_Pair, Array_Type => Priority_Pair_Array);
type Mapping_Candidates is Array(Positive range 1 .. 26) of Character;
type Char_Possibilities is record
c : Encrypted_Char;
num_possible : Natural;
possibilities : Mapping_Candidates;
end record;
type Word_Possibilities is record
is_using_root : Boolean;
words : Word_List.Word_Vector;
end record;
type Guess_Order_Array is Array(Positive range <>) of Positive;
type Char_Possibilities_Array is Array(Positive range <>) of Char_Possibilities;
type Word_Possibilities_Array is Array(Positive range <>) of Word_Possibilities;
type Word_Inclusion is Array(Positive range <>, Positive range <>) of Natural;
type Letter_Toggle is Array(Positive range <>) of Boolean;
type Word_Toggle is Array(Positive range <>) of Boolean;
package Word_Vectors renames Word_List.Word_Vectors;
function "="(a, b: Word_Vectors.Cursor) return Boolean renames Word_Vectors."=";
procedure Free_Word_Vector is new Ada.Unchecked_Deallocation(Object => Word_Vectors.Vector, Name => Word_List.Word_Vector);
type Decipher_State (num_words : Positive; num_letters : Positive) is record
candidates : Candidate_Set(1 .. num_words);
characters : Char_Possibilities_Array(1 .. num_letters);
words : Word_Possibilities_Array(1 .. num_words);
inclusion : Word_Inclusion(1 .. num_letters, 1 .. num_words);
guess_order : Guess_Order_Array(1 .. num_letters);
end record;
function Image(ew: Encrypted_Word) return Word_List.Word is
w : Word_List.Word;
begin
for i in ew'Range loop
w(i) := Character(ew(i));
end loop;
return w;
end Image;
function Get_Character_Index(state : Decipher_State; c : Encrypted_Char) return Positive is
begin
for ci in state.characters'Range loop
if c = state.characters(ci).c then
return ci;
end if;
end loop;
raise Constraint_Error;
end Get_Character_Index;
function Is_Word_Valid(state : Decipher_State; candidate : Encrypted_Word; word : Word_List.Word) return Boolean is
begin
for i in candidate'Range loop
exit when candidate(i) = ' ';
declare
ci : constant Positive := Get_Character_Index(state, candidate(i));
c : constant Character := word(i);
cp : Char_Possibilities renames state.characters(ci);
found : Boolean := False;
begin
if cp.num_possible = 1 then
found := cp.possibilities(1) = c;
elsif cp.num_possible = 26 then
found := True;
else
for j in 1 .. cp.num_possible loop
if cp.possibilities(j) = c then
found := True;
exit;
end if;
end loop;
end if;
if not found then
return False;
end if;
end;
end loop;
return True;
end Is_Word_Valid;
procedure Filter_Word_List(state : Decipher_State; candidate : Encrypted_Word; initial : Word_List.Word_Vector; final : Word_List.Word_Vector) is
cur : Word_Vectors.Cursor := initial.First;
begin
while cur /= Word_Vectors.No_Element loop
if Is_Word_Valid(state, candidate, Word_Vectors.Element(cur)) then
final.Append(Word_Vectors.Element(cur));
end if;
cur := Word_Vectors.Next(cur);
end loop;
end Filter_Word_List;
procedure Put_Possible(cp: Char_Possibilities) is
begin
for i in 1 .. cp.Num_Possible loop
IO.Put(cp.possibilities(i));
end loop;
IO.New_Line;
end Put_Possible;
procedure Put_Inclusion(state: Decipher_State) is
begin
for i in 1 .. state.Num_Letters loop
IO.Put(Encrypted_Char'Image(state.characters(i).c) & ": ");
for j in 1 .. state.Num_Words loop
exit when state.inclusion(i, j) = 0;
IO.Put(Natural'Image(state.inclusion(i, j)));
end loop;
IO.New_Line;
end loop;
end Put_Inclusion;
procedure Make_Unique(state : in out Decipher_State; ci : Positive; success : out Boolean; changed : in out Letter_Toggle) is
letter : constant Character := state.characters(ci).possibilities(1);
begin
success := True;
-- IO.Put_Line("Determined that " & Encrypted_Char'Image(state.characters(ci).c) & " has to be a " & Character'Image(letter));
for i in state.characters'Range loop
if i /= ci then
declare
cp : Char_Possibilities renames state.characters(i);
begin
for j in 1 .. cp.num_possible loop
if cp.possibilities(j) = letter then
if cp.num_possible = 1 then
success := False;
return;
else
-- IO.Put("Before: "); Put_Possible(cp);
cp.possibilities(j .. cp.num_possible - 1) := cp.possibilities(j + 1 .. cp.num_possible);
cp.num_possible := cp.num_possible - 1;
-- IO.Put("After: "); Put_Possible(cp);
changed(i) := True;
if cp.num_possible = 1 then
-- IO.Put_Line("Make_Unique from Make_Unique");
Make_Unique(state, i, success, changed);
if not success then
return;
end if;
end if;
exit;
end if;
end if;
end loop;
end;
end if;
end loop;
end Make_Unique;
procedure Constrain_Letters(state : in out Decipher_State; wi : Positive; success : out Boolean; changed : in out Letter_Toggle) is
ci : Positive;
cur : Word_Vectors.Cursor := state.words(wi).words.all.First;
word : Word_List.Word;
seen : Array(Positive range 1 .. state.num_letters, Character range 'a' .. 'z') of Boolean := (others => (others => False));
used : Array(Positive range 1 .. state.num_letters) of Boolean := (others => False);
begin
success := True;
while cur /= Word_Vectors.No_Element loop
word := Word_Vectors.Element(cur);
for i in word'Range loop
exit when word(i) = ' ';
ci := Get_Character_Index(state, state.candidates(wi)(i));
seen(ci, word(i)) := True;
used(ci) := True;
end loop;
cur := Word_Vectors.Next(cur);
end loop;
for i in used'range loop
if used(i) then
-- IO.Put("Seen: ");
-- for c in Character range 'a' .. 'z' loop
-- if (seen(i, c)) then
-- IO.Put(c);
-- end if;
-- end loop;
-- IO.New_Line;
declare
cp : Char_Possibilities renames state.characters(i);
shrunk : Boolean := False;
write_head : Natural := 0;
begin
-- IO.Put("Before: "); Put_Possible(cp);
for read_head in 1 .. cp.Num_Possible loop
if seen(i, cp.possibilities(read_head)) then
write_head := write_head + 1;
if write_head /= read_head then
cp.possibilities(write_head) := cp.possibilities(read_head);
end if;
else
shrunk := True;
end if;
end loop;
cp.Num_Possible := write_head;
-- IO.Put("After: "); Put_Possible(cp);
if Shrunk then
changed(i) := True;
if cp.Num_Possible = 0 then
success := False;
return;
elsif cp.Num_Possible = 1 then
-- IO.Put_Line("Make_Unique from Constrain_Letters");
Make_Unique(state, i, success, changed);
if not success then
return;
end if;
end if;
end if;
end;
end if;
end loop;
end Constrain_Letters;
procedure Check_Constraints(state : in out Decipher_State; changed : Letter_Toggle; success : out Boolean) is
words : Word_Toggle(1 .. state.num_words) := (others => False);
follow_up : Letter_Toggle(1 .. state.num_letters) := (others => False);
any_changed : Boolean := False;
begin
success := True;
for i in 1 .. state.num_letters loop
if changed(i) then
any_changed := True;
for j in 1 .. state.num_words loop
exit when state.inclusion(i, j) = 0;
words(state.inclusion(i, j)) := True;
end loop;
end if;
end loop;
if not any_changed then
return;
end if;
for i in 1 .. state.num_words loop
if words(i) then
declare
new_words : Word_List.Word_Vector := new Word_Vectors.Vector;
begin
Filter_Word_List(state, state.candidates(i), state.words(i).words, new_words);
if Natural(new_words.Length) = 0 then
Free_Word_Vector(new_words);
success := False;
return;
elsif Natural(new_words.Length) = Natural(state.words(i).words.Length) then
-- IO.Put_Line("Word set for " & Positive'Image(i) & "(" & Image(state.candidates(i)) & ") did not shrink from " & Ada.Containers.Count_Type'Image(state.words(i).words.all.Length));
Free_Word_Vector(new_Words);
else
-- IO.Put_Line("Restricting word set for " & Positive'Image(i) & "(" & Image(state.candidates(i)) & ") from " & Ada.Containers.Count_Type'Image(state.words(i).words.all.Length) & " to " & Ada.Containers.Count_Type'Image(new_words.all.Length));
if state.words(i).is_using_root then
state.words(i).is_using_root := False;
else
Free_Word_Vector(state.words(i).words);
end if;
state.words(i).words := new_words;
Constrain_Letters(state, i, success, follow_up);
if not success then
return;
end if;
end if;
end;
end if;
end loop;
Check_Constraints(state, follow_up, success);
end Check_Constraints;
procedure Guess_Letter(state : in out Decipher_State; gi : Positive) is
begin
if gi > state.num_letters then
IO.Put_Line("Found Solution");
for ci in 1 .. state.num_letters loop
IO.Put(Character(state.characters(ci).c));
if state.characters(ci).num_possible /= 1 then
IO.Put_Line(": Invalid State");
return;
end if;
end loop;
IO.New_Line;
for ci in 1 .. state.num_letters loop
IO.Put(state.characters(ci).possibilities(1));
end loop;
IO.New_Line;
for wi in 1 .. state.num_words loop
IO.Put(Image(state.candidates(wi)) & ": ");
if Natural(state.words(wi).words.all.Length) = 1 then
IO.Put_Line(state.words(wi).words.all(1));
else
IO.Put_Line("*Invalid: " & Ada.Containers.Count_Type'Image(state.words(wi).words.all.Length) & " Words");
end if;
end loop;
IO.Put_Line("--------------------------");
else
declare
ci : constant Positive := state.guess_order(gi);
begin
if state.characters(ci).num_possible = 1 then
-- Nothing to do, pass it up the line
Guess_Letter(state, ci + 1);
else
declare
success : Boolean;
changed : Letter_Toggle(1 .. state.num_letters);
characters : constant Char_Possibilities_Array := state.characters;
words : constant Word_Possibilities_Array := state.words;
cp : Char_Possibilities renames characters(ci);
begin
for mi in 1 .. cp.num_possible loop
changed := (others => False);
changed(ci) := True;
state.characters(ci).possibilities(1) := characters(ci).possibilities(mi);
-- IO.Put_Line("Guessing " & Character'Image(state.characters(ci).possibilities(mi)) & " for " & Encrypted_Char'Image(state.characters(ci).c));
state.characters(ci).num_possible := 1;
for wi in 1 .. state.num_words loop
state.words(wi).is_using_root := True;
end loop;
-- IO.Put_Line("Make_Unique from Guess_Letter");
Make_Unique(state, ci, success, changed);
if success then
Check_Constraints(state, changed, success);
if success then
Guess_Letter(state, ci + 1);
end if;
end if;
-- IO.Put_Line("Restore Letter guess for " & Positive'Image(ci));
state.characters := characters;
state.words := words;
end loop;
end;
end if;
end;
end if;
end Guess_Letter;
function Decipher(candidates: Candidate_Set; words: Word_List.Word_List) return Result_Set is
letters : Character_Sets.Set;
begin
for ci in candidates'Range loop
for i in candidates(ci)'Range loop
exit when candidates(ci)(i) = ' ';
letters.Include(candidates(ci)(i));
end loop;
end loop;
declare
num_words : constant Positive := Positive(candidates'Length);
num_letters : constant Positive := Positive(letters.Length);
result : Result_Set(1 .. num_letters);
state : Decipher_State(num_words, num_letters);
cur : Character_Sets.Cursor := letters.First;
inclusion_priority : Priority_Pair_Array(1 .. num_letters);
begin
state.candidates := candidates;
state.inclusion := (others => (others => 0));
for i in 1 .. num_letters loop
state.characters(i).c := Character_Sets.Element(cur);
state.characters(i).num_possible := 26;
inclusion_priority(i) := (item => i, priority => 0);
for l in Character range 'a' .. 'z' loop
state.characters(i).possibilities(Character'Pos(l) - Character'Pos('a') + 1) := l;
end loop;
cur := Character_Sets.Next(cur);
end loop;
for i in 1 .. num_words loop
for l in candidates(Candidates'First + i - 1)'Range loop
declare
c : constant Encrypted_Char := candidates(Candidates'First + i - 1)(l);
ci : Positive;
begin
exit when c = ' ';
ci := Get_Character_Index(state, c);
for mi in 1 .. num_words loop
if state.inclusion(ci, mi) = 0 then
state.inclusion(ci, mi) := i;
inclusion_priority(ci).priority := mi;
exit;
elsif state.inclusion(ci, mi) = i then
exit;
end if;
end loop;
end;
end loop;
state.words(i).is_using_root := True;
state.words(i).words := words.Element(Word_List.Make_Pattern(Image(candidates(i))));
end loop;
Priority_Pair_Sort(inclusion_priority);
-- Put_Inclusion(state);
for i in inclusion_priority'range loop
state.guess_order(i) := inclusion_priority(i).item;
-- IO.Put_Line("Guess " & Integer'Image(i) & " is " & Encrypted_Char'Image(state.characters(inclusion_priority(i).item).c) & " with " & Integer'Image(inclusion_priority(i).priority) & " words connected to it");
end loop;
Guess_Letter(state, 1);
return result;
end;
end Decipher;
end Decipherer;
|
Sort the letters by word frequency, which removes the performance penalty for rot1 encoding the test input.
|
Sort the letters by word frequency, which removes the performance penalty for rot1
encoding the test input.
I imagine I'm paying a performance penalty for the fact that everything is copying around
24 bytes for every string used (so if I reduce a word list from 3000 words to 2000 words I
copy 2000 24 character words instead of just 2000 integers), but in release mode it
currently runs in .1 seconds on my machine.
For comparison, perl runs in just over 1 second and debug mode runs in about 3/4 of a
second.
|
Ada
|
unlicense
|
Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.