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
444abc38a661d9c6de75e27e2d3bdae410b08f59
openal-context.adb
openal-context.adb
with Ada.IO_Exceptions; with Interfaces.C.Strings; with Interfaces.C; with System; package body OpenAL.Context is package C renames Interfaces.C; package C_Strings renames Interfaces.C.Strings; function Open_Device (Specifier : in String) return Device_t is C_Spec : aliased C.char_array := C.To_C (Specifier); Device : Device_t; begin Device.Device_Data := ALC_Thin.Open_Device (Specifier => C_Spec (C_Spec'First)'Address); return Device; end Open_Device; function Open_Default_Device return Device_t is Device : Device_t; begin Device.Device_Data := ALC_Thin.Open_Device (Specifier => System.Null_Address); return Device; end Open_Default_Device; function Close_Device (Device : in Device_t) return Boolean is begin return Boolean (ALC_Thin.Close_Device (Device.Device_Data)); end Close_Device; function Create_Context (Device : in Device_t) return Context_t is begin return Context_t (ALC_Thin.Create_Context (Device => Device.Device_Data, Attribute_List => System.Null_Address)); end Create_Context; function Make_Context_Current (Context : in Context_t) return Boolean is begin return Boolean (ALC_Thin.Make_Context_Current (ALC_Thin.Context_t (Context))); end Make_Context_Current; procedure Process_Context (Context : in Context_t) is begin ALC_Thin.Process_Context (ALC_Thin.Context_t (Context)); end Process_Context; procedure Suspend_Context (Context : in Context_t) is begin ALC_Thin.Suspend_Context (ALC_Thin.Context_t (Context)); end Suspend_Context; procedure Destroy_Context (Context : in Context_t) is begin ALC_Thin.Destroy_Context (ALC_Thin.Context_t (Context)); end Destroy_Context; function Get_Current_Context return Context_t is begin return Context_t (ALC_Thin.Get_Current_Context); end Get_Current_Context; function Get_Context_Device (Context : in Context_t) return Device_t is Device : Device_t; begin Device.Device_Data := ALC_Thin.Get_Contexts_Device (ALC_Thin.Context_t (Context)); return Device; end Get_Context_Device; function Is_Extension_Present (Device : in Device_t; Name : in String) return Boolean is C_Name : aliased C.char_array := C.To_C (Name); begin return Boolean (ALC_Thin.Is_Extension_Present (Device => Device.Device_Data, Extension_Name => C_Name (C_Name'First)'Address)); end Is_Extension_Present; -- -- String queries -- function Get_String (Device : ALC_Thin.Device_t; Parameter : Types.Enumeration_t) return C_Strings.chars_ptr; pragma Import (C, Get_String, "alcGetString"); use type ALC_Thin.Device_t; Null_Device : constant ALC_Thin.Device_t := ALC_Thin.Device_t (System.Null_Address); function Get_Default_Device_Specifier return String is CS : constant C_Strings.chars_ptr := Get_String (Device => Null_Device, Parameter => ALC_Thin.ALC_DEFAULT_DEVICE_SPECIFIER)); begin if CS /= C_Strings.null_ptr then return C_Strings.Value (CS); else raise Ada.IO_Exceptions.Device_Error with "no device available"; end if; end Get_Default_Device_Specifier; function Get_Device_Specifier (Device : in Device_t) return String is begin if Device.Device_Data = Null_Device then raise Ada.IO_Exceptions.Device_Error with "invalid device"; end if; return C_Strings.Value (Get_String (Device => Device.Device_Data, Parameter => ALC_Thin.ALC_DEVICE_SPECIFIER)); end Get_Device_Specifier; function Get_Extensions (Device : in Device_t) return String is begin if Device.Device_Data = Null_Device then raise Ada.IO_Exceptions.Device_Error with "invalid device"; end if; return C_Strings.Value (Get_String (Device => Device.Device_Data, Parameter => ALC_Thin.ALC_EXTENSIONS)); end Get_Extensions; function Get_Default_Capture_Device_Specifier return String is CS : constant C_Strings.chars_ptr := Get_String (Device => Null_Device, Parameter => ALC_Thin.ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER); begin if CS /= C_Strings.Null_Ptr then return C_Strings.Value (CS); else raise Ada.IO_Exceptions.Device_Error with "no capture device available"; end if; end Get_Default_Capture_Device_Specifier; function Get_Available_Capture_Devices return OpenAL.List.String_Vector_t is Address : System.Address; List : OpenAL.List.String_Vector_t; begin Address := ALC_Thin.Get_String (Device => ALC_Thin.Device_t (System.Null_Address), Token => ALC_Thin.ALC_CAPTURE_DEVICE_SPECIFIER); if Address /= System.Null_Address then OpenAL.List.Address_To_Vector (Address => Address, List => List); end if; return List; end Get_Available_Capture_Devices; function Get_Available_Playback_Devices return OpenAL.List.String_Vector_t is Address : System.Address; List : OpenAL.List.String_Vector_t; begin Address := ALC_Thin.Get_String (Device => ALC_Thin.Device_t (System.Null_Address), Token => ALC_Thin.ALC_DEVICE_SPECIFIER); if Address /= System.Null_Address then OpenAL.List.Address_To_Vector (Address => Address, List => List); end if; return List; end Get_Available_Playback_Devices; -- -- Integer queries -- function Get_Major_Version (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_MAJOR_VERSION, Size => 1, Data => Value'Address); return Natural (Value); end Get_Major_Version; function Get_Minor_Version (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_MINOR_VERSION, Size => 1, Data => Value'Address); return Natural (Value); end Get_Minor_Version; function Get_Capture_Samples (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_CAPTURE_SAMPLES, Size => 1, Data => Value'Address); return Natural (Value); end Get_Capture_Samples; function Get_Frequency (Device : in Device_t) return Types.Frequency_t is Value : aliased Types.Integer_t := Types.Frequency_t'First; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_FREQUENCY, Size => 1, Data => Value'Address); return Types.Frequency_t (Value); end Get_Frequency; function Get_Refresh (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_REFRESH, Size => 1, Data => Value'Address); return Natural (Value); end Get_Refresh; function Get_Synchronous (Device : in Device_t) return Boolean is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_SYNC, Size => 1, Data => Value'Address); return Boolean'Val (Value); end Get_Synchronous; function Get_Mono_Sources (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_MONO_SOURCES, Size => 1, Data => Value'Address); return Natural (Value); end Get_Mono_Sources; function Get_Stereo_Sources (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_STEREO_SOURCES, Size => 1, Data => Value'Address); return Natural (Value); end Get_Stereo_Sources; end OpenAL.Context;
with Ada.IO_Exceptions; with Interfaces.C.Strings; with Interfaces.C; with System; package body OpenAL.Context is package C renames Interfaces.C; package C_Strings renames Interfaces.C.Strings; function Open_Device (Specifier : in String) return Device_t is C_Spec : aliased C.char_array := C.To_C (Specifier); Device : Device_t; begin Device.Device_Data := ALC_Thin.Open_Device (Specifier => C_Spec (C_Spec'First)'Address); return Device; end Open_Device; function Open_Default_Device return Device_t is Device : Device_t; begin Device.Device_Data := ALC_Thin.Open_Device (Specifier => System.Null_Address); return Device; end Open_Default_Device; function Close_Device (Device : in Device_t) return Boolean is begin return Boolean (ALC_Thin.Close_Device (Device.Device_Data)); end Close_Device; function Create_Context (Device : in Device_t) return Context_t is begin return Context_t (ALC_Thin.Create_Context (Device => Device.Device_Data, Attribute_List => System.Null_Address)); end Create_Context; function Make_Context_Current (Context : in Context_t) return Boolean is begin return Boolean (ALC_Thin.Make_Context_Current (ALC_Thin.Context_t (Context))); end Make_Context_Current; procedure Process_Context (Context : in Context_t) is begin ALC_Thin.Process_Context (ALC_Thin.Context_t (Context)); end Process_Context; procedure Suspend_Context (Context : in Context_t) is begin ALC_Thin.Suspend_Context (ALC_Thin.Context_t (Context)); end Suspend_Context; procedure Destroy_Context (Context : in Context_t) is begin ALC_Thin.Destroy_Context (ALC_Thin.Context_t (Context)); end Destroy_Context; function Get_Current_Context return Context_t is begin return Context_t (ALC_Thin.Get_Current_Context); end Get_Current_Context; function Get_Context_Device (Context : in Context_t) return Device_t is Device : Device_t; begin Device.Device_Data := ALC_Thin.Get_Contexts_Device (ALC_Thin.Context_t (Context)); return Device; end Get_Context_Device; function Is_Extension_Present (Device : in Device_t; Name : in String) return Boolean is C_Name : aliased C.char_array := C.To_C (Name); begin return Boolean (ALC_Thin.Is_Extension_Present (Device => Device.Device_Data, Extension_Name => C_Name (C_Name'First)'Address)); end Is_Extension_Present; -- -- String queries -- function Get_String (Device : ALC_Thin.Device_t; Parameter : Types.Enumeration_t) return C_Strings.chars_ptr; pragma Import (C, Get_String, "alcGetString"); use type C_Strings.chars_ptr; use type ALC_Thin.Device_t; use type System.Address; Null_Device : constant ALC_Thin.Device_t := ALC_Thin.Device_t (System.Null_Address); function Get_Default_Device_Specifier return String is CS : constant C_Strings.chars_ptr := Get_String (Device => Null_Device, Parameter => ALC_Thin.ALC_DEFAULT_DEVICE_SPECIFIER); begin if CS /= C_Strings.Null_Ptr then return C_Strings.Value (CS); else raise Ada.IO_Exceptions.Device_Error with "no device available"; end if; end Get_Default_Device_Specifier; function Get_Device_Specifier (Device : in Device_t) return String is begin if Device.Device_Data = Null_Device then raise Ada.IO_Exceptions.Device_Error with "invalid device"; end if; return C_Strings.Value (Get_String (Device => Device.Device_Data, Parameter => ALC_Thin.ALC_DEVICE_SPECIFIER)); end Get_Device_Specifier; function Get_Extensions (Device : in Device_t) return String is begin if Device.Device_Data = Null_Device then raise Ada.IO_Exceptions.Device_Error with "invalid device"; end if; return C_Strings.Value (Get_String (Device => Device.Device_Data, Parameter => ALC_Thin.ALC_EXTENSIONS)); end Get_Extensions; function Get_Default_Capture_Device_Specifier return String is CS : constant C_Strings.chars_ptr := Get_String (Device => Null_Device, Parameter => ALC_Thin.ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER); begin if CS /= C_Strings.Null_Ptr then return C_Strings.Value (CS); else raise Ada.IO_Exceptions.Device_Error with "no capture device available"; end if; end Get_Default_Capture_Device_Specifier; function Get_Available_Capture_Devices return OpenAL.List.String_Vector_t is Address : System.Address; List : OpenAL.List.String_Vector_t; begin Address := ALC_Thin.Get_String (Device => ALC_Thin.Device_t (System.Null_Address), Token => ALC_Thin.ALC_CAPTURE_DEVICE_SPECIFIER); if Address /= System.Null_Address then OpenAL.List.Address_To_Vector (Address => Address, List => List); end if; return List; end Get_Available_Capture_Devices; function Get_Available_Playback_Devices return OpenAL.List.String_Vector_t is Address : System.Address; List : OpenAL.List.String_Vector_t; begin Address := ALC_Thin.Get_String (Device => ALC_Thin.Device_t (System.Null_Address), Token => ALC_Thin.ALC_DEVICE_SPECIFIER); if Address /= System.Null_Address then OpenAL.List.Address_To_Vector (Address => Address, List => List); end if; return List; end Get_Available_Playback_Devices; -- -- Integer queries -- function Get_Major_Version (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_MAJOR_VERSION, Size => 1, Data => Value'Address); return Natural (Value); end Get_Major_Version; function Get_Minor_Version (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_MINOR_VERSION, Size => 1, Data => Value'Address); return Natural (Value); end Get_Minor_Version; function Get_Capture_Samples (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_CAPTURE_SAMPLES, Size => 1, Data => Value'Address); return Natural (Value); end Get_Capture_Samples; function Get_Frequency (Device : in Device_t) return Types.Frequency_t is Value : aliased Types.Integer_t := Types.Integer_t (Types.Frequency_t'First); begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_FREQUENCY, Size => 1, Data => Value'Address); return Types.Frequency_t (Value); end Get_Frequency; function Get_Refresh (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_REFRESH, Size => 1, Data => Value'Address); return Natural (Value); end Get_Refresh; function Get_Synchronous (Device : in Device_t) return Boolean is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_SYNC, Size => 1, Data => Value'Address); return Boolean'Val (Value); end Get_Synchronous; function Get_Mono_Sources (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_MONO_SOURCES, Size => 1, Data => Value'Address); return Natural (Value); end Get_Mono_Sources; function Get_Stereo_Sources (Device : in Device_t) return Natural is Value : aliased Types.Integer_t := 0; begin ALC_Thin.Get_Integerv (Device => Device.Device_Data, Token => ALC_Thin.ALC_STEREO_SOURCES, Size => 1, Data => Value'Address); return Natural (Value); end Get_Stereo_Sources; end OpenAL.Context;
Clean up previous commit...
Clean up previous commit...
Ada
isc
io7m/coreland-openal-ada,io7m/coreland-openal-ada
2531a82dfb13aa7ae55c7f86694aa10a9ca865aa
regtests/util-beans-objects-discrete_tests.adb
regtests/util-beans-objects-discrete_tests.adb
----------------------------------------------------------------------- -- Util.Beans.Objects.Discrete_Tests - Generic simple test for discrete object types -- Copyright (C) 2009, 2010, 2011, 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.Containers; with Ada.Strings.Fixed; with Ada.Text_IO; with Ada.Calendar; with Util.Test_Caller; with Util.Beans.Objects.Hash; package body Util.Beans.Objects.Discrete_Tests is use Ada.Strings.Fixed; use Ada.Containers; procedure Test_Eq (T : Test; V : String; N : Test_Type); procedure Test_Conversion (T : Test; V : String; N : Test_Type); procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type); procedure Test_Sub (T : Test; V : String; N : Test_Type); procedure Test_Add (T : Test; V : String; N : Test_Type); procedure Test_Perf (T : Test; V : String; N : Test_Type); procedure Test_Hash (T : in out Test); -- Generic test for To_Object and To_XXX types -- Several values are specified in the Test_Values string. generic with procedure Basic_Test (T : in Test; V : String; N : Test_Type); procedure Test_Basic_Object (T : in out Test); procedure Test_Basic_Object (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); begin Basic_Test (T, V, N); end; Pos := Next + 1; end loop; end Test_Basic_Object; -- ------------------------------ -- Test Util.Beans.Objects.To_Object -- ------------------------------ procedure Test_Conversion (T : Test; V : String; N : Test_Type) is Value : Util.Beans.Objects.Object; begin Value := To_Object (V); T.Assert (Condition => To_Type (Value) = N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); T.Assert (Condition => V = To_String (Value), Message => Test_Name & ".To_String returned invalid value: " & To_String (Value) & " when we expected: " & V); end Test_Conversion; procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion); -- ------------------------------ -- Test Util.Beans.Objects.Hash -- ------------------------------ procedure Test_Hash (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; Hash_Values : array (Test_Values'Range) of Hash_Type := (others => 0); Nb_Hash : Natural := 0; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); Value : constant Util.Beans.Objects.Object := To_Object_Test (N); H : constant Hash_Type := Util.Beans.Objects.Hash (Value); Found : Boolean := False; begin for J in 1 .. Nb_Hash loop if Hash_Values (J) = H then Found := True; end if; end loop; if not Found then Nb_Hash := Nb_Hash + 1; Hash_Values (Nb_Hash) := H; end if; end; Pos := Next + 1; end loop; Ada.Text_IO.Put_Line ("Found " & Natural'Image (Nb_Hash) & " hash values"); T.Assert (Nb_Hash > 1, "Only one hash value found"); end Test_Hash; -- ------------------------------ -- Test Util.Beans.Objects."+" -- ------------------------------ procedure Test_Add (T : Test; V : String; N : Test_Type) is Value : Util.Beans.Objects.Object := To_Object_Test (N); begin Value := Value + To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N + N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); end Test_Add; procedure Test_Add is new Test_Basic_Object (Test_Add); -- ------------------------------ -- Test Util.Beans.Objects."-" -- ------------------------------ procedure Test_Sub (T : Test; V : String; N : Test_Type) is pragma Unreferenced (V); Value : Util.Beans.Objects.Object; begin Value := To_Object_Test (N) - To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N - N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: 0"); end Test_Sub; procedure Test_Sub is new Test_Basic_Object (Test_Sub); -- ------------------------------ -- Test Util.Beans.Objects."<" and Util.Beans.Objects.">" -- ------------------------------ procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type) is Res : Boolean; Is_Neg : constant Boolean := Index (V, "-") = V'First; O : constant Util.Beans.Objects.Object := To_Object_Test (N); begin Res := To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O)) & " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O))); Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V); if V /= "0" and V /= "false" and V /= "true" then Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); end if; end Test_Lt_Gt; procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt); -- ------------------------------ -- Test Util.Beans.Objects."=" -- ------------------------------ procedure Test_Eq (T : Test; V : String; N : Test_Type) is Res : Boolean; begin Res := To_Object_Test (N) = To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); Res := To_Object_Test (N) = To_Object ("Something" & V); T.Assert (Condition => Res = False, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " where we expected: False"); end Test_Eq; procedure Test_Eq is new Test_Basic_Object (Test_Eq); -- ------------------------------ -- Test Util.Beans.Objects."=" -- ------------------------------ procedure Test_Perf (T : Test; V : String; N : Test_Type) is pragma Unreferenced (T, V); use Ada.Calendar; Start : Ada.Calendar.Time; Value : constant Util.Beans.Objects.Object := To_Object_Test (N); D : Duration; begin Start := Ada.Calendar.Clock; for I in 1 .. 1_000 loop declare V : Util.Beans.Objects.Object := Value; begin V := V + V; pragma Unreferenced (V); end; end loop; D := Ada.Calendar.Clock - Start; Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0)); end Test_Perf; procedure Test_Perf is new Test_Basic_Object (Test_Perf); package Caller is new Util.Test_Caller (Test, "Beans.Objects." & Test_Name); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_Object." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_String." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'='." & Test_Name, Test_Eq'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'+'." & Test_Name, Test_Add'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'-'." & Test_Name, Test_Sub'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'<'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'>'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Performance Util.Beans.Objects.'>'." & Test_Name, Test_Perf'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.Hash." & Test_Name, Test_Hash'Access); end Add_Tests; end Util.Beans.Objects.Discrete_Tests;
----------------------------------------------------------------------- -- Util.Beans.Objects.Discrete_Tests - Generic simple test for discrete object types -- Copyright (C) 2009, 2010, 2011, 2018, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Strings.Fixed; with Ada.Text_IO; with Ada.Calendar; with Util.Test_Caller; with Util.Beans.Objects.Hash; package body Util.Beans.Objects.Discrete_Tests is use Ada.Strings.Fixed; use Ada.Containers; procedure Test_Eq (T : Test; V : String; N : Test_Type); procedure Test_Conversion (T : Test; V : String; N : Test_Type); procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type); procedure Test_Le_Ge (T : Test; V : String; N : Test_Type); procedure Test_Sub (T : Test; V : String; N : Test_Type); procedure Test_Add (T : Test; V : String; N : Test_Type); procedure Test_Perf (T : Test; V : String; N : Test_Type); procedure Test_Hash (T : in out Test); -- Generic test for To_Object and To_XXX types -- Several values are specified in the Test_Values string. generic with procedure Basic_Test (T : in Test; V : String; N : Test_Type); procedure Test_Basic_Object (T : in out Test); procedure Test_Basic_Object (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); begin Basic_Test (T, V, N); end; Pos := Next + 1; end loop; end Test_Basic_Object; -- ------------------------------ -- Test Util.Beans.Objects.To_Object -- ------------------------------ procedure Test_Conversion (T : Test; V : String; N : Test_Type) is Value : Util.Beans.Objects.Object; begin Value := To_Object (V); T.Assert (Condition => To_Type (Value) = N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); T.Assert (Condition => V = To_String (Value), Message => Test_Name & ".To_String returned invalid value: " & To_String (Value) & " when we expected: " & V); end Test_Conversion; procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion); -- ------------------------------ -- Test Util.Beans.Objects.Hash -- ------------------------------ procedure Test_Hash (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; Hash_Values : array (Test_Values'Range) of Hash_Type := (others => 0); Nb_Hash : Natural := 0; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); Value : constant Util.Beans.Objects.Object := To_Object_Test (N); H : constant Hash_Type := Util.Beans.Objects.Hash (Value); Found : Boolean := False; begin for J in 1 .. Nb_Hash loop if Hash_Values (J) = H then Found := True; end if; end loop; if not Found then Nb_Hash := Nb_Hash + 1; Hash_Values (Nb_Hash) := H; end if; end; Pos := Next + 1; end loop; Ada.Text_IO.Put_Line ("Found " & Natural'Image (Nb_Hash) & " hash values"); T.Assert (Nb_Hash > 1, "Only one hash value found"); end Test_Hash; -- ------------------------------ -- Test Util.Beans.Objects."+" -- ------------------------------ procedure Test_Add (T : Test; V : String; N : Test_Type) is Value : Util.Beans.Objects.Object := To_Object_Test (N); begin Value := Value + To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N + N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); end Test_Add; procedure Test_Add is new Test_Basic_Object (Test_Add); -- ------------------------------ -- Test Util.Beans.Objects."-" -- ------------------------------ procedure Test_Sub (T : Test; V : String; N : Test_Type) is pragma Unreferenced (V); Value : Util.Beans.Objects.Object; begin Value := To_Object_Test (N) - To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N - N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: 0"); end Test_Sub; procedure Test_Sub is new Test_Basic_Object (Test_Sub); -- ------------------------------ -- Test Util.Beans.Objects."<" and Util.Beans.Objects.">" -- ------------------------------ procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type) is Res : Boolean; Is_Neg : constant Boolean := Index (V, "-") = V'First; O : constant Util.Beans.Objects.Object := To_Object_Test (N); begin Res := To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O)) & " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O))); Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V); if V /= "0" and V /= "false" and V /= "true" then Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); end if; end Test_Lt_Gt; -- ------------------------------ -- Test Util.Beans.Objects."<" and Util.Beans.Objects.">" -- ------------------------------ procedure Test_Le_Ge (T : Test; V : String; N : Test_Type) is Res : Boolean; Is_Neg : constant Boolean := Index (V, "-") = V'First; O : constant Util.Beans.Objects.Object := To_Object_Test (N); begin Res := To_Object_Test (N) <= To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'<=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); Res := To_Object_Test (N) >= To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'>=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); if To_Object_Test (N) + To_Object_Test (N) /= To_Object_Test (N) then Res := To_Object_Test (N) + To_Object_Test (N) <= To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'<=' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O)) & " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O))); Res := To_Object_Test (N) >= To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V); end if; if V /= "0" and V /= "false" and V /= "true" then Res := To_Object_Test (N) <= To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); Res := To_Object_Test (N) + To_Object_Test (N) >= To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); end if; end Test_Le_Ge; procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt); procedure Test_Le_Ge is new Test_Basic_Object (Test_Le_Ge); -- ------------------------------ -- Test Util.Beans.Objects."=" -- ------------------------------ procedure Test_Eq (T : Test; V : String; N : Test_Type) is Res : Boolean; begin Res := To_Object_Test (N) = To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); Res := To_Object_Test (N) = To_Object ("Something" & V); T.Assert (Condition => Res = False, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " where we expected: False"); end Test_Eq; procedure Test_Eq is new Test_Basic_Object (Test_Eq); -- ------------------------------ -- Test Util.Beans.Objects."=" -- ------------------------------ procedure Test_Perf (T : Test; V : String; N : Test_Type) is pragma Unreferenced (T, V); use Ada.Calendar; Start : Ada.Calendar.Time; Value : constant Util.Beans.Objects.Object := To_Object_Test (N); D : Duration; begin Start := Ada.Calendar.Clock; for I in 1 .. 1_000 loop declare V : Util.Beans.Objects.Object := Value; begin V := V + V; pragma Unreferenced (V); end; end loop; D := Ada.Calendar.Clock - Start; Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0)); end Test_Perf; procedure Test_Perf is new Test_Basic_Object (Test_Perf); package Caller is new Util.Test_Caller (Test, "Beans.Objects." & Test_Name); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_Object." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_String." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'='." & Test_Name, Test_Eq'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'+'." & Test_Name, Test_Add'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'-'." & Test_Name, Test_Sub'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'<'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'>'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'<='." & Test_Name, Test_Le_Ge'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'>='." & Test_Name, Test_Le_Ge'Access); Caller.Add_Test (Suite, "Performance Util.Beans.Objects.'>'." & Test_Name, Test_Perf'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.Hash." & Test_Name, Test_Hash'Access); end Add_Tests; end Util.Beans.Objects.Discrete_Tests;
Add new tests for >= and <= comparisons
Add new tests for >= and <= comparisons
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
fb820e99d205675f37f02aa9e76874daf6a37445
matp/src/mat-targets-probes.adb
matp/src/mat-targets-probes.adb
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ELF; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; M_LIBNAME : constant MAT.Events.Internal_Reference := 6; M_LADDR : constant MAT.Events.Internal_Reference := 7; M_COUNT : constant MAT.Events.Internal_Reference := 8; M_TYPE : constant MAT.Events.Internal_Reference := 9; M_VADDR : constant MAT.Events.Internal_Reference := 10; M_SIZE : constant MAT.Events.Internal_Reference := 11; M_FLAGS : constant MAT.Events.Internal_Reference := 12; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; LIBNAME_NAME : aliased constant String := "libname"; LADDR_NAME : aliased constant String := "laddr"; COUNT_NAME : aliased constant String := "count"; TYPE_NAME : aliased constant String := "type"; VADDR_NAME : aliased constant String := "vaddr"; SIZE_NAME : aliased constant String := "size"; FLAGS_NAME : aliased constant String := "flags"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); Library_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => LIBNAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME), 2 => (Name => LADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_LADDR), 3 => (Name => COUNT_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_COUNT), 4 => (Name => TYPE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_TYPE), 5 => (Name => VADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_VADDR), 6 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_SIZE), 7 => (Name => FLAGS_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FLAGS)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Event.Addr := Heap.Start_Addr; Event.Size := Heap.Size; Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); Probe.Target.Process.Endian := MAT.Readers.Get_Endian (Msg); end Probe_Begin; -- ------------------------------ -- Extract the information from the 'library' event. -- ------------------------------ procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Count : MAT.Types.Target_Size := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Addr : MAT.Types.Target_Addr; Pos : Natural := Defs'Last + 1; Offset : MAT.Types.Target_Addr; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_COUNT => Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); Pos := I + 1; exit; when M_LIBNAME => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_LADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Event.Addr := Addr; Event.Size := 0; for Region in 1 .. Count loop declare Region : MAT.Memory.Region_Info; Kind : ELF.Elf32_Word := 0; begin for I in Pos .. Defs'Last loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_VADDR => Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_TYPE => Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when M_FLAGS => Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; if Kind = ELF.PT_LOAD then Region.Start_Addr := Addr + Region.Start_Addr; Region.End_Addr := Region.Start_Addr + Region.Size; if Ada.Strings.Unbounded.Length (Path) = 0 then Region.Path := Probe.Target.Process.Path; Offset := 0; else Region.Path := Path; Offset := Region.Start_Addr; end if; Event.Size := Event.Size + Region.Size; Probe.Target.Process.Memory.Add_Region (Region); -- When auto-symbol loading is enabled, load the symbols associated with the -- shared libraries used by the program. if Probe.Target.Options.Load_Symbols then begin Probe.Target.Process.Symbols.Value.Load_Symbols (Region, Offset); end; end if; end if; end; end loop; end Probe_Library; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Events.Targets.Probe_Index_Type; begin if Event.Index = MAT.Events.Targets.MSG_BEGIN then Probe.Probe_Begin (Params.all, Msg, Event); elsif Event.Index = MAT.Events.Targets.MSG_LIBRARY then Probe.Probe_Library (Params.all, Msg, Event); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MAT.Events.Targets.MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MAT.Events.Targets.MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MAT.Events.Targets.MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ELF; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; M_LIBNAME : constant MAT.Events.Internal_Reference := 6; M_LADDR : constant MAT.Events.Internal_Reference := 7; M_COUNT : constant MAT.Events.Internal_Reference := 8; M_TYPE : constant MAT.Events.Internal_Reference := 9; M_VADDR : constant MAT.Events.Internal_Reference := 10; M_SIZE : constant MAT.Events.Internal_Reference := 11; M_FLAGS : constant MAT.Events.Internal_Reference := 12; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; LIBNAME_NAME : aliased constant String := "libname"; LADDR_NAME : aliased constant String := "laddr"; COUNT_NAME : aliased constant String := "count"; TYPE_NAME : aliased constant String := "type"; VADDR_NAME : aliased constant String := "vaddr"; SIZE_NAME : aliased constant String := "size"; FLAGS_NAME : aliased constant String := "flags"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); Library_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => LIBNAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME), 2 => (Name => LADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_LADDR), 3 => (Name => COUNT_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_COUNT), 4 => (Name => TYPE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_TYPE), 5 => (Name => VADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_VADDR), 6 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_SIZE), 7 => (Name => FLAGS_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FLAGS)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Event.Addr := Heap.Start_Addr; Event.Size := Heap.Size; Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); Probe.Target.Process.Endian := MAT.Readers.Get_Endian (Msg); end Probe_Begin; -- ------------------------------ -- Extract the information from the 'library' event. -- ------------------------------ procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Count : MAT.Types.Target_Size := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Addr : MAT.Types.Target_Addr; Pos : Natural := Defs'Last + 1; Offset : MAT.Types.Target_Addr; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_COUNT => Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); Pos := I + 1; exit; when M_LIBNAME => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_LADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Event.Addr := Addr; Event.Size := 0; for Region in 1 .. Count loop declare Region : MAT.Memory.Region_Info; Kind : ELF.Elf32_Word := 0; begin for I in Pos .. Defs'Last loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_VADDR => Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_TYPE => Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when M_FLAGS => Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; if Kind = ELF.PT_LOAD then Region.Start_Addr := Addr + Region.Start_Addr; Region.End_Addr := Region.Start_Addr + Region.Size; if Ada.Strings.Unbounded.Length (Path) = 0 then Region.Path := Probe.Target.Process.Path; Offset := 0; else Region.Path := Path; Offset := Region.Start_Addr; end if; Event.Size := Event.Size + Region.Size; Probe.Target.Process.Memory.Add_Region (Region); -- When auto-symbol loading is enabled, load the symbols associated with the -- shared libraries used by the program. if Probe.Target.Options.Load_Symbols then begin Probe.Target.Process.Symbols.Value.Load_Symbols (Region, Offset); end; end if; end if; end; end loop; end Probe_Library; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Events.Targets.Probe_Index_Type; begin if Event.Index = MAT.Events.Targets.MSG_BEGIN then Probe.Probe_Begin (Params.all, Msg, Event); elsif Event.Index = MAT.Events.Targets.MSG_LIBRARY then Probe.Probe_Library (Params.all, Msg, Event); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MAT.Events.Targets.MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MAT.Events.Targets.MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MAT.Events.Targets.MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
Change the Event parameter of Execute to an in out parameter
Change the Event parameter of Execute to an in out parameter
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
bb2ba7875019e0d388c3f8cb0e460afc8578b9d9
src/ravenports.adb
src/ravenports.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Parameters; with HelperText; with Unix; with File_Operations; with Ada.Directories; with Ada.Text_IO; package body Ravenports is package PM renames Parameters; package HT renames HelperText; package FOP renames File_Operations; package TIO renames Ada.Text_IO; package DIR renames Ada.Directories; -------------------------------------------------------------------------------------------- -- check_version_available -------------------------------------------------------------------------------------------- procedure check_version_available is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); version_loc : constant String := consdir & conspiracy_version; begin if DIR.Exists (version_loc) then if fetch_latest_version_info (temporary_ver_loc) then declare currentver : constant String := FOP.head_n1 (version_loc); latestver : constant String := FOP.head_n1 (temporary_ver_loc); begin if latestver = currentver then TIO.Put_Line ("The latest version of Ravenports, " & latestver & ", is currently installed."); else TIO.Put_Line ("A newer version of Ravenports is available: " & latestver); TIO.Put_Line ("The " & currentver & " version is currently installed."); end if; end; DIR.Delete_File (temporary_ver_loc); end if; else TIO.Put_Line ("It appears that Ravenports has not been installed at " & consdir); end if; exception when others => null; end check_version_available; -------------------------------------------------------------------------------------------- -- fetch_latest_version_info -------------------------------------------------------------------------------------------- function fetch_latest_version_info (tmp_location : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); fetch_program : constant String := sysroot & "/usr/bin/fetch"; cmd_output : HT.Text; cmd : constant String := fetch_program & " -q --no-verify-peer " & remote_version & " -o " & tmp_location; use type DIR.File_Kind; begin if not DIR.Exists ("/tmp") or else DIR.Kind ("/tmp") /= DIR.Directory then TIO.Put_Line ("The /tmp directory does not exist, bailing ..."); return False; end if; if not DIR.Exists (fetch_program) then TIO.Put_Line ("It appears that the system root has not yet been installed at " & sysroot); TIO.Put_Line ("This must be rectified before Ravenports can be checked or fetched."); return False; end if; return Unix.piped_mute_command (cmd, cmd_output); end fetch_latest_version_info; -------------------------------------------------------------------------------------------- -- fetch_latest_tarball -------------------------------------------------------------------------------------------- function fetch_latest_tarball (latest_version : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); fetch_program : constant String := sysroot & "/usr/bin/fetch"; tarball : constant String := github_archive & "/" & latest_version & ".tar.gz"; cmd_output : HT.Text; cmd : constant String := fetch_program & " -q " & tarball & " -o /tmp"; begin -- covered by previous existence checks of fetch_latest_version_info return Unix.piped_mute_command (cmd, cmd_output); end fetch_latest_tarball; -------------------------------------------------------------------------------------------- -- later_version_available -------------------------------------------------------------------------------------------- function later_version_available (available : out Boolean) return String is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); version_loc : constant String := consdir & conspiracy_version; begin available := True; -- We know consdir exists because we couldn't get here if it didn't. if fetch_latest_version_info (temporary_ver_loc) then declare latestver : constant String := FOP.head_n1 (temporary_ver_loc); begin DIR.Delete_File (temporary_ver_loc); if DIR.Exists (version_loc) then declare currentver : constant String := FOP.head_n1 (version_loc); begin if latestver = currentver then available := False; end if; end; end if; return latestver; end; else available := False; TIO.Put_Line ("Failed to fetch latest version information from Github"); return ""; end if; end later_version_available; -------------------------------------------------------------------------------------------- -- retrieve_latest_ravenports -------------------------------------------------------------------------------------------- procedure retrieve_latest_ravenports is available : Boolean; latest_version : constant String := later_version_available (available); begin if not available then TIO.Put_Line ("Ravenports update skipped as no new version is available."); return; end if; clean_up (latest_version); if not fetch_latest_tarball (latest_version) then TIO.Put_Line ("Ravenports update skipped as tarball download failed."); return; end if; if relocate_existing_ravenports and then explode_tarball_into_conspiracy (latest_version) then clean_up (latest_version); end if; end retrieve_latest_ravenports; -------------------------------------------------------------------------------------------- -- retrieve_latest_ravenports -------------------------------------------------------------------------------------------- function relocate_existing_ravenports return Boolean is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); consdir_old : constant String := consdir & ".old"; begin DIR.Rename (Old_Name => consdir, New_Name => consdir_old); return True; exception when others => return False; end relocate_existing_ravenports; -------------------------------------------------------------------------------------------- -- explode_tarball_into_conspiracy -------------------------------------------------------------------------------------------- function explode_tarball_into_conspiracy (latest_version : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); mv_program : constant String := sysroot & "/bin/mv "; tar_program : constant String := sysroot & "/usr/bin/tar "; tarball : constant String := "/tmp/" & latest_version & ".tar.gz"; extract_dir : constant String := "/tmp/Ravenports-" & latest_version; cmd_output : HT.Text; command : constant String := tar_program & "-C /tmp -xf " & tarball; command2 : constant String := mv_program & extract_dir & " " & consdir; begin if Unix.piped_mute_command (command, cmd_output) then return Unix.piped_mute_command (command2, cmd_output); else return False; end if; end explode_tarball_into_conspiracy; -------------------------------------------------------------------------------------------- -- clean_up -------------------------------------------------------------------------------------------- procedure clean_up (latest_version : String) is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); consdir_old : constant String := consdir & ".old"; extract_old : constant String := "/tmp/Ravenports-" & latest_version; command : constant String := sysroot & "/bin/rm -rf " & consdir_old; command2 : constant String := sysroot & "/bin/rm -rf " & extract_old; tarball : constant String := "/tmp/" & latest_version & ".tar.gz"; cmd_output : HT.Text; success : Boolean; begin if DIR.Exists (consdir_old) then success := Unix.piped_mute_command (command, cmd_output); end if; if DIR.Exists (tarball) then DIR.Delete_File (tarball); end if; if DIR.Exists (extract_old) then success := Unix.piped_mute_command (command2, cmd_output); end if; exception when others => null; end clean_up; end Ravenports;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Parameters; with HelperText; with Unix; with File_Operations; with Ada.Directories; with Ada.Text_IO; package body Ravenports is package PM renames Parameters; package HT renames HelperText; package FOP renames File_Operations; package TIO renames Ada.Text_IO; package DIR renames Ada.Directories; -------------------------------------------------------------------------------------------- -- check_version_available -------------------------------------------------------------------------------------------- procedure check_version_available is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); version_loc : constant String := consdir & conspiracy_version; begin if DIR.Exists (version_loc) then if fetch_latest_version_info (temporary_ver_loc) then declare currentver : constant String := FOP.head_n1 (version_loc); latestver : constant String := FOP.head_n1 (temporary_ver_loc); begin if latestver = currentver then TIO.Put_Line ("The latest version of Ravenports, " & latestver & ", is currently installed."); else TIO.Put_Line ("A newer version of Ravenports is available: " & latestver); TIO.Put_Line ("The " & currentver & " version is currently installed."); end if; end; DIR.Delete_File (temporary_ver_loc); end if; else TIO.Put_Line ("It appears that Ravenports has not been installed at " & consdir); end if; exception when others => null; end check_version_available; -------------------------------------------------------------------------------------------- -- fetch_latest_version_info -------------------------------------------------------------------------------------------- function fetch_latest_version_info (tmp_location : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); fetch_program : constant String := sysroot & "/usr/bin/fetch"; cmd_output : HT.Text; cmd : constant String := fetch_program & " -q --no-verify-peer " & remote_version & " -o " & tmp_location; use type DIR.File_Kind; begin if not DIR.Exists ("/tmp") or else DIR.Kind ("/tmp") /= DIR.Directory then TIO.Put_Line ("The /tmp directory does not exist, bailing ..."); return False; end if; if not DIR.Exists (fetch_program) then TIO.Put_Line ("It appears that the system root has not yet been installed at " & sysroot); TIO.Put_Line ("This must be rectified before Ravenports can be checked or fetched."); return False; end if; return Unix.piped_mute_command (cmd, cmd_output); end fetch_latest_version_info; -------------------------------------------------------------------------------------------- -- fetch_latest_tarball -------------------------------------------------------------------------------------------- function fetch_latest_tarball (latest_version : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); fetch_program : constant String := sysroot & "/usr/bin/fetch"; tarball : constant String := github_archive & "/" & latest_version & ".tar.gz"; cmd_output : HT.Text; cmd : constant String := fetch_program & " -q " & tarball & " -o /tmp"; begin -- covered by previous existence checks of fetch_latest_version_info return Unix.piped_mute_command (cmd, cmd_output); end fetch_latest_tarball; -------------------------------------------------------------------------------------------- -- later_version_available -------------------------------------------------------------------------------------------- function later_version_available (available : out Boolean) return String is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); version_loc : constant String := consdir & conspiracy_version; begin available := True; -- We know consdir exists because we couldn't get here if it didn't. if fetch_latest_version_info (temporary_ver_loc) then declare latestver : constant String := FOP.head_n1 (temporary_ver_loc); begin DIR.Delete_File (temporary_ver_loc); if DIR.Exists (version_loc) then declare currentver : constant String := FOP.head_n1 (version_loc); begin if latestver = currentver then available := False; end if; end; end if; return latestver; end; else available := False; TIO.Put_Line ("Failed to fetch latest version information from Github"); return ""; end if; end later_version_available; -------------------------------------------------------------------------------------------- -- retrieve_latest_ravenports -------------------------------------------------------------------------------------------- procedure retrieve_latest_ravenports is available : Boolean; latest_version : constant String := later_version_available (available); begin if not available then TIO.Put_Line ("Ravenports update skipped as no new version is available."); return; end if; clean_up (latest_version); if not fetch_latest_tarball (latest_version) then TIO.Put_Line ("Ravenports update skipped as tarball download failed."); return; end if; if relocate_existing_ravenports and then explode_tarball_into_conspiracy (latest_version) then clean_up (latest_version); TIO.Put_Line ("Ravenports updated to version " & latest_version); end if; end retrieve_latest_ravenports; -------------------------------------------------------------------------------------------- -- retrieve_latest_ravenports -------------------------------------------------------------------------------------------- function relocate_existing_ravenports return Boolean is consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); consdir_old : constant String := consdir & ".old"; begin DIR.Rename (Old_Name => consdir, New_Name => consdir_old); return True; exception when others => return False; end relocate_existing_ravenports; -------------------------------------------------------------------------------------------- -- explode_tarball_into_conspiracy -------------------------------------------------------------------------------------------- function explode_tarball_into_conspiracy (latest_version : String) return Boolean is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); mv_program : constant String := sysroot & "/bin/mv "; tar_program : constant String := sysroot & "/usr/bin/tar "; tarball : constant String := "/tmp/" & latest_version & ".tar.gz"; extract_dir : constant String := "/tmp/Ravenports-" & latest_version; cmd_output : HT.Text; command : constant String := tar_program & "-C /tmp -xf " & tarball; command2 : constant String := mv_program & extract_dir & " " & consdir; begin if Unix.piped_mute_command (command, cmd_output) then return Unix.piped_mute_command (command2, cmd_output); else return False; end if; end explode_tarball_into_conspiracy; -------------------------------------------------------------------------------------------- -- clean_up -------------------------------------------------------------------------------------------- procedure clean_up (latest_version : String) is sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); consdir : constant String := HT.USS (PM.configuration.dir_conspiracy); consdir_old : constant String := consdir & ".old"; extract_old : constant String := "/tmp/Ravenports-" & latest_version; command : constant String := sysroot & "/bin/rm -rf " & consdir_old; command2 : constant String := sysroot & "/bin/rm -rf " & extract_old; tarball : constant String := "/tmp/" & latest_version & ".tar.gz"; cmd_output : HT.Text; success : Boolean; begin if DIR.Exists (consdir_old) then success := Unix.piped_mute_command (command, cmd_output); end if; if DIR.Exists (tarball) then DIR.Delete_File (tarball); end if; if DIR.Exists (extract_old) then success := Unix.piped_mute_command (command2, cmd_output); end if; exception when others => null; end clean_up; end Ravenports;
Add positive feedback to success ravenports update
Add positive feedback to success ravenports update requested-by: dillon
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
8159c51fb1709b12ee0e3f37a9c55b99a4b94067
src/wiki-nodes.adb
src/wiki-nodes.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Nodes is -- ------------------------------ -- Create a text node. -- ------------------------------ function Create_Text (Text : in WString) return Node_Type_Access is begin return new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, others => <>); end Create_Text; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Nodes is -- ------------------------------ -- Create a text node. -- ------------------------------ function Create_Text (Text : in WString) return Node_Type_Access is begin return new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, others => <>); end Create_Text; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; end Wiki.Nodes;
Implement the Append procedure
Implement the Append procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
e5cfea9c2f1a0fce71f5011efc9be77c7a18dbbb
src/wiki-utils.adb
src/wiki-utils.adb
----------------------------------------------------------------------- -- wiki-utils -- Wiki utility operations -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Render.Text; with Wiki.Render.Html; with Wiki.Filters.Html; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; package body Wiki.Utils is -- ------------------------------ -- Render the wiki text according to the wiki syntax in HTML into a string. -- ------------------------------ function To_Html (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Stream'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Text, Renderer'Unchecked_Access); return Stream.To_String; end To_Html; -- ------------------------------ -- Render the wiki text according to the wiki syntax in text into a string. -- Wiki formatting and decoration are removed. -- ------------------------------ function To_Text (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Stream'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Text, Renderer'Unchecked_Access); return Stream.To_String; end To_Text; end Wiki.Utils;
----------------------------------------------------------------------- -- wiki-utils -- Wiki utility operations -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Render.Text; with Wiki.Render.Html; with Wiki.Filters.Html; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; with Wiki.Nodes; package body Wiki.Utils is -- ------------------------------ -- Render the wiki text according to the wiki syntax in HTML into a string. -- ------------------------------ function To_Html (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; Doc : Wiki.Nodes.Document; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Stream'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Text, Doc); Renderer.Render (Doc); return Stream.To_String; end To_Html; -- ------------------------------ -- Render the wiki text according to the wiki syntax in text into a string. -- Wiki formatting and decoration are removed. -- ------------------------------ function To_Text (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Doc : Wiki.Nodes.Document; Renderer : aliased Wiki.Render.Text.Text_Renderer; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Stream'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Text, Doc); Renderer.Render (Doc); return Stream.To_String; end To_Text; end Wiki.Utils;
Update the To_Html and To_Text to parse into a document and render the result
Update the To_Html and To_Text to parse into a document and render the result
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
3d25084ffe582cbe600ab45d76317d2c2bbf58a1
src/asf-beans-mappers.ads
src/asf-beans-mappers.ads
----------------------------------------------------------------------- -- asf-beans-mappers -- Read XML managed bean declaratiosn -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; with EL.Contexts; package ASF.Beans.Mappers is type Managed_Bean_Fields is (FIELD_NAME, FIELD_CLASS, FIELD_SCOPE, FIELD_MANAGED_BEAN, FIELD_PROPERTY, FIELD_PROPERTY_NAME, FIELD_PROPERTY_VALUE, FIELD_PROPERTY_CLASS); type Bean_Factory_Access is access all ASF.Beans.Bean_Factory; type Managed_Bean is record Name : Util.Beans.Objects.Object; Class : Util.Beans.Objects.Object; Scope : Scope_Type := REQUEST_SCOPE; Factory : Bean_Factory_Access := null; Params : ASF.Beans.Parameter_Bean_Ref.Ref; Prop_Name : Util.Beans.Objects.Object; Prop_Value : Util.Beans.Objects.Object; Context : EL.Contexts.ELContext_Access := null; end record; type Managed_Bean_Access is access all Managed_Bean; -- Set the field identified by <b>Field</b> with the <b>Value</b>. procedure Set_Member (MBean : in out Managed_Bean; Field : in Managed_Bean_Fields; Value : in Util.Beans.Objects.Object); -- Setup the XML parser to read the managed bean definitions. generic Reader : in out Util.Serialize.IO.XML.Parser; Factory : in Bean_Factory_Access; Context : in EL.Contexts.ELContext_Access; package Reader_Config is Config : aliased Managed_Bean; end Reader_Config; private package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Managed_Bean, Element_Type_Access => Managed_Bean_Access, Fields => Managed_Bean_Fields, Set_Member => Set_Member); end ASF.Beans.Mappers;
----------------------------------------------------------------------- -- asf-beans-mappers -- Read XML managed bean declaratiosn -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; with EL.Contexts; package ASF.Beans.Mappers is type Managed_Bean_Fields is (FIELD_NAME, FIELD_CLASS, FIELD_SCOPE, FIELD_MANAGED_BEAN, FIELD_PROPERTY, FIELD_PROPERTY_NAME, FIELD_PROPERTY_VALUE, FIELD_PROPERTY_CLASS); type Bean_Factory_Access is access all ASF.Beans.Bean_Factory; type Managed_Bean is limited record Name : Util.Beans.Objects.Object; Class : Util.Beans.Objects.Object; Scope : Scope_Type := REQUEST_SCOPE; Factory : Bean_Factory_Access := null; Params : ASF.Beans.Parameter_Bean_Ref.Ref; Prop_Name : Util.Beans.Objects.Object; Prop_Value : Util.Beans.Objects.Object; Context : EL.Contexts.ELContext_Access := null; end record; type Managed_Bean_Access is access all Managed_Bean; -- Set the field identified by <b>Field</b> with the <b>Value</b>. procedure Set_Member (MBean : in out Managed_Bean; Field : in Managed_Bean_Fields; Value : in Util.Beans.Objects.Object); -- Setup the XML parser to read the managed bean definitions. generic Reader : in out Util.Serialize.IO.XML.Parser; Factory : in Bean_Factory_Access; Context : in EL.Contexts.ELContext_Access; package Reader_Config is Config : aliased Managed_Bean; end Reader_Config; private package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Managed_Bean, Element_Type_Access => Managed_Bean_Access, Fields => Managed_Bean_Fields, Set_Member => Set_Member); end ASF.Beans.Mappers;
Use a limited record for Managed_Bean since we don't need to copy these objects and this reduces the code size
Use a limited record for Managed_Bean since we don't need to copy these objects and this reduces the code size
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
07b9d6f2ed2f07b2edcd98e237c57e6cb5115740
src/el-methods-proc_1.ads
src/el-methods-proc_1.ads
----------------------------------------------------------------------- -- EL.Methods.Proc_1 -- Procedure Binding with 1 argument -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Contexts; with Util.Beans.Methods; with Util.Beans.Basic; generic type Param1_Type (<>) is limited private; package EL.Methods.Proc_1 is use Util.Beans.Methods; -- Returns True if the method is a valid method which accepts the arguments -- defined by the package instantiation. function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean; -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in out Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. procedure Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in out Param1_Type; Context : in EL.Contexts.ELContext'Class); -- Execute the method describe by the method binding object. -- The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in out Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. procedure Execute (Method : in EL.Expressions.Method_Info; Param : in out Param1_Type); -- Function access to the proxy. type Proxy_Access is access procedure (O : access Util.Beans.Basic.Readonly_Bean'Class; P : in out Param1_Type); -- The binding record which links the method name -- to the proxy function. type Binding is new Method_Binding with record Method : Proxy_Access; end record; type Binding_Access is access constant Binding; -- Proxy for the binding. -- The proxy declares the binding definition that links -- the name to the function and it implements the necessary -- object conversion to translate the <b>Readonly_Bean</b> -- object to the target object type. generic -- Name of the method (as exposed in the EL expression) Name : String; -- The bean type type Bean is abstract new Util.Beans.Basic.Readonly_Bean with private; -- The bean method to invoke with procedure Method (O : in out Bean; P1 : in out Param1_Type); package Bind is -- Method that <b>Execute</b> will invoke. procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class; P1 : in out Param1_Type); F_NAME : aliased constant String := Name; -- The proxy binding that can be exposed through -- the <b>Method_Bean</b> interface. Proxy : aliased constant Binding := Binding '(Name => F_NAME'Access, Method => Method_Access'Access); end Bind; end EL.Methods.Proc_1;
----------------------------------------------------------------------- -- EL.Methods.Proc_1 -- Procedure Binding with 1 argument -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Contexts; with Util.Beans.Methods; with Util.Beans.Basic; generic type Param1_Type (<>) is limited private; package EL.Methods.Proc_1 is use Util.Beans.Methods; -- Returns True if the method is a valid method which accepts the arguments -- defined by the package instantiation. function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean; -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in out Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. procedure Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in out Param1_Type; Context : in EL.Contexts.ELContext'Class); -- Execute the method describe by the method binding object. -- The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in out Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. procedure Execute (Method : in EL.Expressions.Method_Info; Param : in out Param1_Type); -- Function access to the proxy. type Proxy_Access is access procedure (O : access Util.Beans.Basic.Readonly_Bean'Class; P : in out Param1_Type); -- The binding record which links the method name -- to the proxy function. type Binding is new Method_Binding with record Method : Proxy_Access; end record; type Binding_Access is access constant Binding; -- Proxy for the binding. -- The proxy declares the binding definition that links -- the name to the function and it implements the necessary -- object conversion to translate the <b>Readonly_Bean</b> -- object to the target object type. generic -- Name of the method (as exposed in the EL expression) Name : String; -- The bean type type Bean is abstract limited new Util.Beans.Basic.Readonly_Bean with private; -- The bean method to invoke with procedure Method (O : in out Bean; P1 : in out Param1_Type); package Bind is -- Method that <b>Execute</b> will invoke. procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class; P1 : in out Param1_Type); F_NAME : aliased constant String := Name; -- The proxy binding that can be exposed through -- the <b>Method_Bean</b> interface. Proxy : aliased constant Binding := Binding '(Name => F_NAME'Access, Method => Method_Access'Access); end Bind; end EL.Methods.Proc_1;
Update the Bind generic package to use a limited type for the Bean type
Update the Bind generic package to use a limited type for the Bean type
Ada
apache-2.0
stcarrez/ada-el
2a381ec080440b16c7cc8860367b72f201096f98
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Log.Loggers; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; with Security.Permissions; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Positive'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); -- package Role_Config is -- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); -- pragma Warnings (Off, Role_Config); begin Log.Info ("Reading policy file {0}", File); Reader.Parse (File); end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is begin null; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Log.Loggers; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; with Security.Permissions; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Positive'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); -- package Role_Config is -- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); -- pragma Warnings (Off, Role_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Set_Reader_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is begin null; end Finalize; end Security.Policies;
Configure the XML reader for each policy that was registered in the policy manager
Configure the XML reader for each policy that was registered in the policy manager
Ada
apache-2.0
Letractively/ada-security
2f8cf818b8f4067c6840d4e5128bc01fd46ca0df
src/wiki-filters-collectors.adb
src/wiki-filters-collectors.adb
----------------------------------------------------------------------- -- wiki-filters-collectors -- Wiki word and link collectors -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters.Collectors is procedure Add_String (Into : in out WString_Maps.Map; Item : in Wiki.Strings.WString) is procedure Increment (Key : in Wiki.Strings.WString; Value : in out Natural) is pragma Unreferenced (Key); begin Value := Value + 1; end Increment; Pos : constant WString_Maps.Cursor := Into.Find (Item); begin if WString_Maps.Has_Element (Pos) then Into.Update_Element (Pos, Increment'Access); else Into.Insert (Item, 1); end if; end Add_String; function Find (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Cursor is begin return Map.Items.Find (Item); end Find; function Contains (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Boolean is begin return Map.Items.Contains (Item); end Contains; procedure Iterate (Map : in Collector_Type; Process : not null access procedure (Pos : in Cursor)) is begin Map.Items.Iterate (Process); end Iterate; -- ------------------------------ -- Word Collector type -- ------------------------------ procedure Collect_Words (Filter : in out Word_Collector_Type; Content : in Wiki.Strings.WString) is Pos : Natural := Content'First; Start : Natural := Content'First; C : Wiki.Strings.WChar; begin while Pos <= Content'Last loop C := Content (Pos); if Wiki.Strings.Is_Alphanumeric (C) then null; else if Start + 1 < Pos - 1 then Add_String (Filter.Items, Content (Start .. Pos - 1)); end if; Start := Pos + 1; end if; Pos := Pos + 1; end loop; if Start < Content'Last then Add_String (Filter.Items, Content (Start .. Content'Last)); end if; end Collect_Words; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin Filter.Collect_Words (Text); Filter_Type (Filter).Add_Text (Document, Text, Format); end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin Filter.Collect_Words (Header); Filter_Type (Filter).Add_Header (Document, Header, Level); end Add_Header; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Filter_Type (Filter).Add_Link (Document, Name, Attributes); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Filter_Type (Filter).Add_Image (Document, Name, Attributes); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Filter_Type (Filter).Add_Quote (Document, Name, Attributes); end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin Filter.Collect_Words (Text); Filter_Type (Filter).Add_Preformatted (Document, Text, Format); end Add_Preformatted; procedure Collect_Link (Filter : in out Link_Collector_Type; Attributes : in Wiki.Attributes.Attribute_List; Name : in String) is Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attributes, Name); begin if Href'Length > 0 then Add_String (Filter.Items, Href); end if; end Collect_Link; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Collect_Link (Filter, Attributes, "href"); Filter_Type (Filter).Add_Link (Document, Name, Attributes); end Add_Link; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ overriding procedure Push_Node (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Tag = A_TAG then Collect_Link (Filter, Attributes, "href"); end if; Filter_Type (Filter).Push_Node (Document, Tag, Attributes); end Push_Node; end Wiki.Filters.Collectors;
----------------------------------------------------------------------- -- wiki-filters-collectors -- Wiki word and link collectors -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters.Collectors is procedure Add_String (Into : in out WString_Maps.Map; Item : in Wiki.Strings.WString); procedure Add_String (Into : in out WString_Maps.Map; Item : in Wiki.Strings.WString) is procedure Increment (Key : in Wiki.Strings.WString; Value : in out Natural); procedure Increment (Key : in Wiki.Strings.WString; Value : in out Natural) is pragma Unreferenced (Key); begin Value := Value + 1; end Increment; Pos : constant WString_Maps.Cursor := Into.Find (Item); begin if WString_Maps.Has_Element (Pos) then Into.Update_Element (Pos, Increment'Access); else Into.Insert (Item, 1); end if; end Add_String; function Find (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Cursor is begin return Map.Items.Find (Item); end Find; function Contains (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Boolean is begin return Map.Items.Contains (Item); end Contains; procedure Iterate (Map : in Collector_Type; Process : not null access procedure (Pos : in Cursor)) is begin Map.Items.Iterate (Process); end Iterate; -- ------------------------------ -- Word Collector type -- ------------------------------ procedure Collect_Words (Filter : in out Word_Collector_Type; Content : in Wiki.Strings.WString) is Pos : Natural := Content'First; Start : Natural := Content'First; C : Wiki.Strings.WChar; begin while Pos <= Content'Last loop C := Content (Pos); if Wiki.Strings.Is_Alphanumeric (C) then null; else if Start + 1 < Pos - 1 then Add_String (Filter.Items, Content (Start .. Pos - 1)); end if; Start := Pos + 1; end if; Pos := Pos + 1; end loop; if Start < Content'Last then Add_String (Filter.Items, Content (Start .. Content'Last)); end if; end Collect_Words; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin Filter.Collect_Words (Text); Filter_Type (Filter).Add_Text (Document, Text, Format); end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin Filter.Collect_Words (Header); Filter_Type (Filter).Add_Header (Document, Header, Level); end Add_Header; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Filter_Type (Filter).Add_Link (Document, Name, Attributes); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Filter_Type (Filter).Add_Image (Document, Name, Attributes); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Filter_Type (Filter).Add_Quote (Document, Name, Attributes); end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin Filter.Collect_Words (Text); Filter_Type (Filter).Add_Preformatted (Document, Text, Format); end Add_Preformatted; procedure Collect_Link (Filter : in out Link_Collector_Type; Attributes : in Wiki.Attributes.Attribute_List; Name : in String) is Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attributes, Name); begin if Href'Length > 0 then Add_String (Filter.Items, Href); end if; end Collect_Link; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Collect_Link (Filter, Attributes, "href"); Filter_Type (Filter).Add_Link (Document, Name, Attributes); end Add_Link; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ overriding procedure Push_Node (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Tag = A_TAG then Collect_Link (Filter, Attributes, "href"); end if; Filter_Type (Filter).Push_Node (Document, Tag, Attributes); end Push_Node; end Wiki.Filters.Collectors;
Declare Add_String and Increment procedures
Declare Add_String and Increment procedures
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
2488f7b5a80af06f54b26ea0dcf08d53214be180
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK => Image : Boolean; Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_QUOTE => Quote_Attr : Wiki.Attributes.Attribute_List_Type; Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- Append the text with the given format at end of the document. procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a link. procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_QUOTE => Quote_Attr : Wiki.Attributes.Attribute_List_Type; Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- Append the text with the given format at end of the document. procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a link. procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
Add N_IMAGE node type
Add N_IMAGE node type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
3a8ab7822e51ac56aacc25cd8ef8336b697d95a3
src/gen-model-tables.ads
src/gen-model-tables.ads
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; Bean : Util.Beans.Objects.Object; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
Add a bean object in the column definition
Add a bean object in the column definition
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
29403b4f5d5a1c268fc291be536570041ae8aa97
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; 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", 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; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test 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; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : 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 M.Add_Policy (R.all'Access); M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); R.Add_Role_Type (Name => "admin", Result => Admin_Perm); R.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); -- end; -- -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/list.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); -- end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (1); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); -- -- Admin_Perm := M.Find_Role (Role); -- -- Context.Set_Context (Manager => M'Unchecked_Access, -- Principal => User'Unchecked_Access); -- -- declare -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- -- A user without the role should not have the permission. -- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was granted for user without role. URI=" & URI); -- -- -- Set the role. -- User.Roles (Admin_Perm) := True; -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was not granted for user with role. URI=" & URI); -- end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.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; 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", 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; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test 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; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : 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 M.Add_Policy (R.all'Access); M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); R.Add_Role_Type (Name => "admin", Result => Admin_Perm); R.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); -- end; -- -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/list.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); -- end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (1); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); -- -- Admin_Perm := M.Find_Role (Role); -- -- Context.Set_Context (Manager => M'Unchecked_Access, -- Principal => User'Unchecked_Access); -- -- declare -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- -- A user without the role should not have the permission. -- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was granted for user without role. URI=" & URI); -- -- -- Set the role. -- User.Roles (Admin_Perm) := True; -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was not granted for user with role. URI=" & URI); -- end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Fix compilation
Fix compilation
Ada
apache-2.0
Letractively/ada-security
0d09bc47e562d0131dc393c980db3ea44a7aaf20
regtests/util-serialize-io-form-tests.adb
regtests/util-serialize-io-form-tests.adb
----------------------------------------------------------------------- -- util-serialize-io-form-tests -- Unit tests for form parser -- 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.Streams.Stream_IO; with Ada.Characters.Wide_Wide_Latin_1; with Ada.Calendar.Formatting; with Util.Test_Caller; with Util.Log.Loggers; with Util.Streams.Files; with Util.Beans.Objects.Readers; package body Util.Serialize.IO.Form.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.Form"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.Form"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Write", Test_Output'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Read", Test_Read'Access); end Add_Tests; -- ------------------------------ -- Check various form parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is procedure Check_Parse_Error (Content : in String); procedure Check_Parse_Error (Content : in String) is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse_String (Content, R); Log.Error ("No exception raised for: {0}", Content); T.Fail ("No exception for " & Content); exception when Parse_Error => null; end Check_Parse_Error; begin -- Check_Parse_Error ("bad"); Check_Parse_Error ("bad=%rw%ad"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSformON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is procedure Check_Parse (Content : in String); procedure Check_Parse (Content : in String) is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse_String (Content, R); exception when Parse_Error => Log.Error ("Parse error for: " & Content); T.Fail ("Parse error for: " & Content); end Check_Parse; begin Check_Parse ("name=value"); Check_Parse ("name=value&param=value"); Check_Parse ("name+name=value+value"); Check_Parse ("name%20%30=value%23%ce"); end Test_Parser; -- ------------------------------ -- Generate some output stream for the test. -- ------------------------------ procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is Name : Ada.Strings.Unbounded.Unbounded_String; Wide : constant Wide_Wide_String := Ada.Characters.Wide_Wide_Latin_1.CR & Ada.Characters.Wide_Wide_Latin_1.LF & Ada.Characters.Wide_Wide_Latin_1.HT & Wide_Wide_Character'Val (16#080#) & Wide_Wide_Character'Val (16#1fC#) & Wide_Wide_Character'Val (16#20AC#) & -- Euro sign Wide_Wide_Character'Val (16#2acbf#); T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0); begin Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen"); Stream.Start_Document; Stream.Start_Entity ("root"); Stream.Start_Entity ("person"); Stream.Write_Attribute ("id", 1); Stream.Write_Attribute ("name", Name); Stream.Write_Entity ("name", Name); Stream.Write_Entity ("gender", "female"); Stream.Write_Entity ("volunteer", True); Stream.Write_Entity ("age", 17); Stream.Write_Entity ("date", T); Stream.Write_Wide_Entity ("skin", "olive skin"); Stream.Start_Array ("badges"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "hunter"); Stream.End_Entity ("badge"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "archery"); Stream.End_Entity ("badge"); Stream.End_Array ("badges"); Stream.Start_Entity ("district"); Stream.Write_Attribute ("id", 12); Stream.Write_Wide_Attribute ("industry", "Coal mining"); Stream.Write_Attribute ("state", "<destroyed>"); Stream.Write_Long_Entity ("members", 10_000); Stream.Write_Entity ("description", "<TBW>&"""); Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+="); Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+="); Stream.Write_Wide_Entity ("wide", Wide); Stream.End_Entity ("district"); Stream.End_Entity ("person"); Stream.End_Entity ("root"); Stream.End_Document; end Write_Stream; -- ------------------------------ -- Test the JSON output stream generation. -- ------------------------------ procedure Test_Output (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Buffer : aliased Util.Streams.Texts.Print_Stream; Stream : Util.Serialize.IO.Form.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.form"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.form"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, Size => 10000); Stream.Initialize (Output => Buffer'Unchecked_Access); Write_Stream (Stream); Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "Form output serialization"); end Test_Output; -- ------------------------------ -- Test reading a form content into an Object tree. -- ------------------------------ procedure Test_Read (T : in out Test) is use Util.Beans.Objects; Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass-01.form"); Root : Util.Beans.Objects.Object; Value : Util.Beans.Objects.Object; begin Root := Read (Path); T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object"); T.Assert (not Util.Beans.Objects.Is_Array (Root), "Root object is not an array"); Value := Util.Beans.Objects.Get_Value (Root, "home"); Util.Tests.Assert_Equals (T, "Cosby", Util.Beans.Objects.To_String (Value), "Invalid first parameter"); Value := Util.Beans.Objects.Get_Value (Root, "favorite flavor"); Util.Tests.Assert_Equals (T, "flies", Util.Beans.Objects.To_String (Value), "Invalid second parameter"); end Test_Read; end Util.Serialize.IO.Form.Tests;
----------------------------------------------------------------------- -- util-serialize-io-form-tests -- Unit tests for form parser -- 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.Streams.Stream_IO; with Ada.Characters.Wide_Wide_Latin_1; with Ada.Calendar.Formatting; with Util.Test_Caller; with Util.Log.Loggers; with Util.Streams.Files; with Util.Beans.Objects.Readers; package body Util.Serialize.IO.Form.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.Form"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.Form"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Write", Test_Output'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Read", Test_Read'Access); end Add_Tests; -- ------------------------------ -- Check various form parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is procedure Check_Parse_Error (Content : in String); procedure Check_Parse_Error (Content : in String) is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse_String (Content, R); T.Assert (P.Has_Error, "No error detected for '" & Content & "'"); end Check_Parse_Error; begin Check_Parse_Error ("bad"); Check_Parse_Error ("bad=%rw%ad"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSformON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is procedure Check_Parse (Content : in String); procedure Check_Parse (Content : in String) is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse_String (Content, R); exception when Parse_Error => Log.Error ("Parse error for: " & Content); T.Fail ("Parse error for: " & Content); end Check_Parse; begin Check_Parse ("name=value"); Check_Parse ("name=value&param=value"); Check_Parse ("name+name=value+value"); Check_Parse ("name%20%30=value%23%ce"); end Test_Parser; -- ------------------------------ -- Generate some output stream for the test. -- ------------------------------ procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is Name : Ada.Strings.Unbounded.Unbounded_String; Wide : constant Wide_Wide_String := Ada.Characters.Wide_Wide_Latin_1.CR & Ada.Characters.Wide_Wide_Latin_1.LF & Ada.Characters.Wide_Wide_Latin_1.HT & Wide_Wide_Character'Val (16#080#) & Wide_Wide_Character'Val (16#1fC#) & Wide_Wide_Character'Val (16#20AC#) & -- Euro sign Wide_Wide_Character'Val (16#2acbf#); T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0); begin Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen"); Stream.Start_Document; Stream.Start_Entity ("root"); Stream.Start_Entity ("person"); Stream.Write_Attribute ("id", 1); Stream.Write_Attribute ("name", Name); Stream.Write_Entity ("name", Name); Stream.Write_Entity ("gender", "female"); Stream.Write_Entity ("volunteer", True); Stream.Write_Entity ("age", 17); Stream.Write_Entity ("date", T); Stream.Write_Wide_Entity ("skin", "olive skin"); Stream.Start_Array ("badges"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "hunter"); Stream.End_Entity ("badge"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "archery"); Stream.End_Entity ("badge"); Stream.End_Array ("badges"); Stream.Start_Entity ("district"); Stream.Write_Attribute ("id", 12); Stream.Write_Wide_Attribute ("industry", "Coal mining"); Stream.Write_Attribute ("state", "<destroyed>"); Stream.Write_Long_Entity ("members", 10_000); Stream.Write_Entity ("description", "<TBW>&"""); Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+="); Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+="); Stream.Write_Wide_Entity ("wide", Wide); Stream.End_Entity ("district"); Stream.End_Entity ("person"); Stream.End_Entity ("root"); Stream.End_Document; end Write_Stream; -- ------------------------------ -- Test the JSON output stream generation. -- ------------------------------ procedure Test_Output (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Buffer : aliased Util.Streams.Texts.Print_Stream; Stream : Util.Serialize.IO.Form.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.form"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.form"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, Size => 10000); Stream.Initialize (Output => Buffer'Unchecked_Access); Write_Stream (Stream); Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "Form output serialization"); end Test_Output; -- ------------------------------ -- Test reading a form content into an Object tree. -- ------------------------------ procedure Test_Read (T : in out Test) is use Util.Beans.Objects; Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass-01.form"); Root : Util.Beans.Objects.Object; Value : Util.Beans.Objects.Object; begin Root := Read (Path); T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object"); T.Assert (not Util.Beans.Objects.Is_Array (Root), "Root object is not an array"); Value := Util.Beans.Objects.Get_Value (Root, "home"); Util.Tests.Assert_Equals (T, "Cosby", Util.Beans.Objects.To_String (Value), "Invalid first parameter"); Value := Util.Beans.Objects.Get_Value (Root, "favorite flavor"); Util.Tests.Assert_Equals (T, "flies", Util.Beans.Objects.To_String (Value), "Invalid second parameter"); end Test_Read; end Util.Serialize.IO.Form.Tests;
Fix the Test_Parse_Error test to verify that we detect a bad format for form-url streams
Fix the Test_Parse_Error test to verify that we detect a bad format for form-url streams
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f4f1b975c55cd11791a350397e2a3fc35adfde40
mat/src/mat-formats.adb
mat/src/mat-formats.adb
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Formats is -- ------------------------------ -- 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 return Hex; 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; 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. ----------------------------------------------------------------------- package body MAT.Formats is -- ------------------------------ -- 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 return Hex; 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; 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; end MAT.Formats;
Implement the Location function to format a file,line,function code location
Implement the Location function to format a file,line,function code location
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1373bf9138c61968abc541812a6166cd289ba368
mat/src/frames/mat-frames-print.adb
mat/src/frames/mat-frames-print.adb
----------------------------------------------------------------------- -- Frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; use Ada.Text_IO; with MAT.Types; with Interfaces; procedure MAT.Frames.Print (File : in File_Type; F : in Frame_Type) is use MAT.Types; use Interfaces; Depth : Natural := F.Depth - F.Local_Depth + 1; Child : Frame_Type; procedure Print_Address (File : in File_Type; Addr : in Target_Addr); function Hex_Image (Val : Target_Addr; Len : Positive) return String; function Hex_Image (Val : Target_Addr; Len : Positive) return String is Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Len) := (others => '0'); P : Target_Addr := Val; N : Target_Addr; I : Positive := Len; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; procedure Print_Address (File : in File_Type; Addr : in Target_Addr) is begin Put (File, Hex_Image (Addr, 20)); end Print_Address; begin for I in 1 .. F.Local_Depth loop Set_Col (File, Positive_Count (Depth)); Print_Address (File, F.Calls (I)); Put_Line (" D " & Natural'Image (Depth)); Depth := Depth + 1; end loop; Child := F.Children; while Child /= null loop Print (File, Child); Child := Child.Next; end loop; end MAT.Frames.Print;
----------------------------------------------------------------------- -- Frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; use Ada.Text_IO; with MAT.Types; with System.Address_Image; with Interfaces; procedure MAT.Frames.Print (File : in File_Type; F : in Frame_Type) is use MAT.Types; use Interfaces; Depth : Natural := F.Depth - F.Local_Depth + 1; Child : Frame_Type; procedure Print_Address (File : in File_Type; Addr : in Target_Addr); function Hex_Image (Val : Target_Addr; Len : Positive) return String; function Hex_Image (Val : Target_Addr; Len : Positive) return String is Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Len) := (others => '0'); P : Target_Addr := Val; N : Target_Addr; I : Positive := Len; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; procedure Print_Address (File : in File_Type; Addr : in Target_Addr) is begin Put (File, Hex_Image (Addr, 20)); end Print_Address; begin Set_Col (File, Positive_Count (Depth)); if F.Parent = null then Put_Line (File, "R " & Natural'Image (F.Used) & " - " & System.Address_Image (F.all'Address)); else Put_Line (File, "F " & Natural'Image (F.Used) & " - " & System.Address_Image (F.all'Address) & " - P=" & System.Address_Image (F.Parent.all'Address)); end if; for I in 1 .. F.Local_Depth loop Set_Col (File, Positive_Count (Depth)); Print_Address (File, F.Calls (I)); Put_Line (File, " D " & Natural'Image (Depth)); Depth := Depth + 1; end loop; Child := F.Children; while Child /= null loop Print (File, Child); Child := Child.Next; end loop; end MAT.Frames.Print;
Print the frame object address for debugging purposes
Print the frame object address for debugging purposes
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
21f4db4c24aeff88bd976b07564d4d522cc10f53
tools/druss-commands.ads
tools/druss-commands.ads
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Util.Commands.Consoles; with Util.Commands.Consoles.Text; with Druss.Gateways; package Druss.Commands is -- The list of fields that are printed on the console. type Field_Type is (F_IP_ADDR, F_WAN_IP, F_INTERNET, F_VOIP, F_WIFI, F_WIFI5, F_ACCESS_CONTROL, F_DYNDNS, F_DEVICES, F_COUNT, F_BOOL, F_CHANNEL, F_PROTOCOL, F_ENCRYPTION, F_SSID); -- The type of notice that are reported. type Notice_Type is (N_HELP, N_INFO); -- Make the generic abstract console interface. package Consoles is new Util.Commands.Consoles (Field_Type => Field_Type, Notice_Type => Notice_Type); -- And the text console to write on stdout (a Gtk console could be done someday). package Text_Consoles is new Consoles.Text; type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; Console : Consoles.Console_Access; end record; package Drivers is new Util.Commands.Drivers (Context_Type => Context_Type, Driver_Name => "druss-drivers"); subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type); procedure Initialize; -- Print the bbox API status. procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); end Druss.Commands;
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Util.Commands.Consoles; with Util.Commands.Consoles.Text; with Druss.Gateways; package Druss.Commands is -- The list of fields that are printed on the console. type Field_Type is (F_IP_ADDR, F_WAN_IP, F_INTERNET, F_VOIP, F_WIFI, F_WIFI5, F_ACCESS_CONTROL, F_DYNDNS, F_DEVICES, F_COUNT, F_BOOL, F_CHANNEL, F_PROTOCOL, F_ENCRYPTION, F_SSID); -- The type of notice that are reported. type Notice_Type is (N_HELP, N_INFO); -- Make the generic abstract console interface. package Consoles is new Util.Commands.Consoles (Field_Type => Field_Type, Notice_Type => Notice_Type); -- And the text console to write on stdout (a Gtk console could be done someday). package Text_Consoles is new Consoles.Text; type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; Console : Consoles.Console_Access; end record; package Drivers is new Util.Commands.Drivers (Context_Type => Context_Type, Driver_Name => "druss-drivers"); subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type); procedure Initialize; -- Print the bbox API status. procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a ON/OFF status. procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); end Druss.Commands;
Declare Print_On_Off procedure
Declare Print_On_Off procedure
Ada
apache-2.0
stcarrez/bbox-ada-api
87abba764647adb95ba26991ac1eda2454bc7ddb
src/babel-base-text.ads
src/babel-base-text.ads
----------------------------------------------------------------------- -- babel-base -- Database for files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Babel.Files.Sets; with Babel.Files.Lifecycles; package Babel.Base.Text is type Text_Database is new Database with private; -- Insert the file in the database. overriding procedure Insert (Into : in out Text_Database; File : in Babel.Files.File_Type); -- -- -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. -- procedure On_Create (Instance : in Text_Database; -- Item : in Babel.Files.File_Type); -- -- -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- procedure On_Update (Instance : in Text_Database; -- Item : in Babel.Files.File_Type); -- -- -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. -- procedure On_Delete (Instance : in Text_Database; -- Item : in Babel.Files.File_Type); -- Write the SHA1 checksum for the files stored in the map. -- ------------------------------ procedure Save (Database : in Text_Database; Path : in String); private type Text_Database is new Database with record Files : Babel.Files.Sets.File_Set; end record; end Babel.Base.Text;
----------------------------------------------------------------------- -- babel-base -- Database for files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Babel.Files.Sets; with Babel.Files.Lifecycles; package Babel.Base.Text is type Text_Database is new Database with private; -- Insert the file in the database. overriding procedure Insert (Into : in out Text_Database; File : in Babel.Files.File_Type); overriding procedure Iterate (From : in Text_Database; Process : not null access procedure (File : in Babel.Files.File_Type)); -- -- -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. -- procedure On_Create (Instance : in Text_Database; -- Item : in Babel.Files.File_Type); -- -- -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- procedure On_Update (Instance : in Text_Database; -- Item : in Babel.Files.File_Type); -- -- -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. -- procedure On_Delete (Instance : in Text_Database; -- Item : in Babel.Files.File_Type); -- Write the SHA1 checksum for the files stored in the map. -- ------------------------------ procedure Save (Database : in Text_Database; Path : in String); private type Text_Database is new Database with record Files : Babel.Files.Sets.File_Set; end record; end Babel.Base.Text;
Declare the Iterate procedure
Declare the Iterate procedure
Ada
apache-2.0
stcarrez/babel
523cdb73c37612cd144e51b3cf96cb2ef024e38c
src/wiki-utils.adb
src/wiki-utils.adb
----------------------------------------------------------------------- -- wiki-utils -- Wiki utility operations -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Parsers; with Wiki.Render.Text; with Wiki.Render.Html; with Wiki.Filters.Html; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; with Wiki.Documents; package body Wiki.Utils is -- ------------------------------ -- Render the wiki text according to the wiki syntax in HTML into a string. -- ------------------------------ function To_Html (Text : in Wide_Wide_String; Syntax : in Wiki.Wiki_Syntax) return String is Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; Doc : Wiki.Documents.Document; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Stream'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Text, Doc); Renderer.Render (Doc); return Stream.To_String; end To_Html; -- ------------------------------ -- Render the wiki text according to the wiki syntax in text into a string. -- Wiki formatting and decoration are removed. -- ------------------------------ function To_Text (Text : in Wide_Wide_String; Syntax : in Wiki.Wiki_Syntax) return String is Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Doc : Wiki.Documents.Document; Renderer : aliased Wiki.Render.Text.Text_Renderer; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Stream'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Text, Doc); Renderer.Render (Doc); return Stream.To_String; end To_Text; end Wiki.Utils;
----------------------------------------------------------------------- -- wiki-utils -- Wiki utility operations -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Parsers; with Wiki.Render.Text; with Wiki.Render.Html; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; with Wiki.Documents; package body Wiki.Utils is -- ------------------------------ -- Render the wiki text according to the wiki syntax in HTML into a string. -- ------------------------------ function To_Html (Text : in Wide_Wide_String; Syntax : in Wiki.Wiki_Syntax) return String is Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; Doc : Wiki.Documents.Document; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Stream'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Text, Doc); Renderer.Render (Doc); return Stream.To_String; end To_Html; -- ------------------------------ -- Render the wiki text according to the wiki syntax in text into a string. -- Wiki formatting and decoration are removed. -- ------------------------------ function To_Text (Text : in Wide_Wide_String; Syntax : in Wiki.Wiki_Syntax) return String is Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Doc : Wiki.Documents.Document; Renderer : aliased Wiki.Render.Text.Text_Renderer; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Stream'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Text, Doc); Renderer.Render (Doc); return Stream.To_String; end To_Text; end Wiki.Utils;
Add the TOC filter to render the TOC
Add the TOC filter to render the TOC
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
fc99f9eceab8875e077b3f13edcabf6773e9e297
matp/src/mat-targets-probes.ads
matp/src/mat-targets-probes.ads
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Events; with MAT.Events.Targets; with MAT.Events.Probes; package MAT.Targets.Probes is type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record Target : Target_Type_Access; Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Events : MAT.Events.Targets.Target_Events_Access; end record; type Process_Probe_Type_Access is access all Process_Probe_Type'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Extract the probe information from the message. overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type); procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access); -- Initialize the target object to prepare for reading process events. procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); private procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type); -- Extract the information from the 'library' event. procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type); end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Events; with MAT.Events.Targets; with MAT.Events.Probes; package MAT.Targets.Probes is type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record Target : Target_Type_Access; Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Events : MAT.Events.Targets.Target_Events_Access; end record; type Process_Probe_Type_Access is access all Process_Probe_Type'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Extract the probe information from the message. overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type); procedure Execute (Probe : in Process_Probe_Type; Event : in out MAT.Events.Targets.Probe_Event_Type); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access); -- Initialize the target object to prepare for reading process events. procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); private procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type); -- Extract the information from the 'library' event. procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type); end MAT.Targets.Probes;
Change the Event parameter of Execute to an in out parameter
Change the Event parameter of Execute to an in out parameter
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
244cb10f1eab8dcc6d1a063090c4d24a7839a255
regtests/asf-applications-views-tests.adb
regtests/asf-applications-views-tests.adb
----------------------------------------------------------------------- -- Render Tests - Unit tests for ASF.Applications.Views -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AUnit.Simple_Test_Cases; with Ada.Text_IO; with ASF.Applications.Views; with ASF.Components.Core; with EL.Contexts; with EL.Contexts.Default; with EL.Variables.Default; with ASF.Contexts.Writer.Tests; with Ada.Directories; with Util.Tests; with Util.Files; with Util.Measures; package body ASF.Applications.Views.Tests is use AUnit; use Ada.Strings.Unbounded; use ASF.Contexts.Writer.Tests; overriding procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- Set up performed before each test case overriding procedure Tear_Down (T : in out Test) is begin null; end Tear_Down; -- Tear down performed after each test case -- Test loading of facelet file procedure Test_Load_Facelet (T : in out Test) is use ASF; use ASF.Contexts.Faces; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; H : Applications.Views.View_Handler; View_Name : constant String := To_String (T.File); Result_File : constant String := To_String (T.Result); Conf : Applications.Config; begin Conf.Load_Properties ("regtests/view.properties"); H.Initialize (Conf); for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Writer : aliased Test_Writer; Context : aliased Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Resolver : aliased Default_ELResolver; begin Context.Set_Response_Writer (Writer'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Writer.Initialize ("text/xml", "UTF-8", 8192); Set_Current (Context'Unchecked_Access); H.Restore_View (View_Name, Context, View); H.Render_View (Context, View); Writer.Flush; Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view " & View_Name); Util.Files.Write_File (Result_File, Writer.Response); Util.Tests.Assert_Equal_Files (Expect => To_String (T.Expect), Test => Result_File, Message => "Restore and render view"); end; end loop; end Test_Load_Facelet; type Test_Case is new AUnit.Simple_Test_Cases.Test_Case with record Name : Unbounded_String; File : Unbounded_String; Expect : Unbounded_String; Result : Unbounded_String; Fixture : Test; end record; type Test_Case_Access is access all Test_Case; -- Test case name overriding function Name (Test : Test_Case) return Message_String; -- Perform the test. overriding procedure Run_Test (Test : in out Test_Case); overriding procedure Set_Up (Test : in out Test_Case); -- Test case name overriding function Name (Test : Test_Case) return Message_String is begin return Format ("Test " & To_String (Test.Name)); end Name; -- Perform the test. overriding procedure Run_Test (Test : in out Test_Case) is begin Test.Fixture.Test_Load_Facelet; end Run_Test; overriding procedure Set_Up (Test : in out Test_Case) is begin Test.Fixture.File := Test.File; Test.Fixture.Expect := Test.Expect; Test.Fixture.Result := Test.Result; Test.Fixture.Set_Up; end Set_Up; procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is use Ada.Directories; Result_Dir : constant String := "regtests/result/views"; Dir : constant String := "regtests/files/views"; Expect_Dir : constant String := "regtests/expect/views"; Path : constant String := Util.Tests.Get_Path (Dir); Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir); Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir); Search : Search_Type; Filter : Filter_Type := (others => True); Ent : Directory_Entry_Type; begin if Kind (Path) = Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); File_Path : constant String := Full_Name (Ent); Test : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" then Test := new Test_Case; Test.Name := To_Unbounded_String (Dir & "/" & Simple); Test.File := To_Unbounded_String (File_Path); Test.Expect := To_Unbounded_String (Expect_Path & "/" & Simple); Test.Result := To_Unbounded_String (Result_Path & "/" & Simple); Suite.Add_Test (Test); end if; end; end loop; end Add_Tests; end ASF.Applications.Views.Tests;
----------------------------------------------------------------------- -- Render Tests - Unit tests for ASF.Applications.Views -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AUnit.Simple_Test_Cases; with Ada.Text_IO; with ASF.Applications.Views; with ASF.Components.Core; with EL.Contexts; with EL.Contexts.Default; with EL.Variables.Default; with ASF.Contexts.Writer.Tests; with Ada.Directories; with Util.Tests; with Util.Files; with Util.Measures; package body ASF.Applications.Views.Tests is use AUnit; use Ada.Strings.Unbounded; use ASF.Contexts.Writer.Tests; overriding procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- Set up performed before each test case overriding procedure Tear_Down (T : in out Test) is begin null; end Tear_Down; -- Tear down performed after each test case -- Test loading of facelet file procedure Test_Load_Facelet (T : in out Test) is use ASF; use ASF.Contexts.Faces; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; H : Applications.Views.View_Handler; View_Name : constant String := To_String (T.File); Result_File : constant String := To_String (T.Result); Conf : Applications.Config; begin Conf.Load_Properties ("regtests/view.properties"); H.Initialize (Conf); for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Writer : aliased Test_Writer; Context : aliased Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Resolver : aliased Default_ELResolver; begin Context.Set_Response_Writer (Writer'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); ELContext.Set_Resolver (Resolver'Unchecked_Access); Writer.Initialize ("text/xml", "UTF-8", 8192); Set_Current (Context'Unchecked_Access); H.Restore_View (View_Name, Context, View); H.Render_View (Context, View); Writer.Flush; Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view " & View_Name); Util.Files.Write_File (Result_File, Writer.Response); Util.Tests.Assert_Equal_Files (Expect => To_String (T.Expect), Test => Result_File, Message => "Restore and render view"); end; end loop; end Test_Load_Facelet; type Test_Case is new AUnit.Simple_Test_Cases.Test_Case with record Name : Unbounded_String; File : Unbounded_String; Expect : Unbounded_String; Result : Unbounded_String; Fixture : Test; end record; type Test_Case_Access is access all Test_Case; -- Test case name overriding function Name (Test : Test_Case) return Message_String; -- Perform the test. overriding procedure Run_Test (Test : in out Test_Case); overriding procedure Set_Up (Test : in out Test_Case); -- Test case name overriding function Name (Test : Test_Case) return Message_String is begin return Format ("Test " & To_String (Test.Name)); end Name; -- Perform the test. overriding procedure Run_Test (Test : in out Test_Case) is begin Test.Fixture.Test_Load_Facelet; end Run_Test; overriding procedure Set_Up (Test : in out Test_Case) is begin Test.Fixture.File := Test.File; Test.Fixture.Expect := Test.Expect; Test.Fixture.Result := Test.Result; Test.Fixture.Set_Up; end Set_Up; procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is use Ada.Directories; Result_Dir : constant String := "regtests/result/views"; Dir : constant String := "regtests/files/views"; Expect_Dir : constant String := "regtests/expect/views"; Path : constant String := Util.Tests.Get_Path (Dir); Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir); Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir); Search : Search_Type; Filter : Filter_Type := (others => True); Ent : Directory_Entry_Type; begin if Kind (Path) = Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); File_Path : constant String := Full_Name (Ent); Test : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" then Test := new Test_Case; Test.Name := To_Unbounded_String (Dir & "/" & Simple); Test.File := To_Unbounded_String (File_Path); Test.Expect := To_Unbounded_String (Expect_Path & "/" & Simple); Test.Result := To_Unbounded_String (Result_Path & "/" & Simple); Suite.Add_Test (Test); end if; end; end loop; end Add_Tests; end ASF.Applications.Views.Tests;
Update unit test
Update unit test
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
237342ce25f034ab76a636b1d05e025ed4a2d09e
tools/druss-commands.adb
tools/druss-commands.adb
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; package body Druss.Commands is Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type) is begin if Args.Get_Count < Arg_Pos + 1 then Druss.Commands.Driver.Usage (Args); end if; declare Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); end Initialize; -- ------------------------------ -- Print the bbox API status. -- ------------------------------ procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "2" then Console.Print_Field (Field, "OK"); elsif Value = "-1" then Console.Print_Field (Field, "KO"); elsif Value = "1" then Console.Print_Field (Field, "Starting"); elsif Value = "0" then Console.Print_Field (Field, "Stopped"); else Console.Print_Field (Field, "?"); end if; end Print_Status; end Druss.Commands;
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; package body Druss.Commands is Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type) is begin if Args.Get_Count < Arg_Pos + 1 then Druss.Commands.Driver.Usage (Args); end if; declare Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); end Initialize; -- ------------------------------ -- Print the bbox API status. -- ------------------------------ procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "2" then Console.Print_Field (Field, "OK"); elsif Value = "-1" then Console.Print_Field (Field, "KO"); elsif Value = "1" then Console.Print_Field (Field, "Starting"); elsif Value = "0" then Console.Print_Field (Field, "Stopped"); else Console.Print_Field (Field, "?"); end if; end Print_Status; -- ------------------------------ -- Print a ON/OFF status. -- ------------------------------ procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "1" then Console.Print_Field (Field, "ON"); elsif Value = "0" then Console.Print_Field (Field, "OFF"); else Console.Print_Field (Field, ""); end if; end Print_On_Off; end Druss.Commands;
Implement the Print_On_Off procedure
Implement the Print_On_Off procedure
Ada
apache-2.0
stcarrez/bbox-ada-api
eba77dcca26bd6a6f6d3592aa1b4960e9261629a
awa/plugins/awa-setup/src/awa-commands-setup.adb
awa/plugins/awa-setup/src/awa-commands-setup.adb
----------------------------------------------------------------------- -- awa-commands-setup -- Setup command to start and configure the application -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Applications; with AWA.Setup.Applications; with Servlet.Core; package body AWA.Commands.Setup is use AWA.Applications; package Command_Drivers renames Start_Command.Command_Drivers; overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); procedure Find_Application (Name : in String); procedure Enable_Application (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; procedure Find_Application (Name : in String) is procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin App.Disable; if URI (URI'First + 1 .. URI'Last) = Name then if App.all in Application'Class then Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin Command_Drivers.WS.Iterate (Find'Access); end Find_Application; procedure Enable_Application (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is pragma Unreferenced (URI); begin App.Enable; App.Start; end Enable_Application; S : aliased AWA.Setup.Applications.Application; begin if Args.Get_Count /= 1 then Context.Console.Notice (N_ERROR, -("Missing application name")); return; end if; declare Name : constant String := Args.Get_Argument (1); begin Find_Application (Name); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Command.Configure_Server (Context); Command.Start_Server (Context); S.Setup (Name, Command_Drivers.WS); Command.Configure_Applications (Context); S.Status.Set (AWA.Setup.Applications.READY); delay 2.0; Command_Drivers.WS.Remove_Application (S'Unchecked_Access); Command_Drivers.WS.Iterate (Enable_Application'Access); Command.Wait_Server (Context); end; end Execute; -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin Start_Command.Command_Type (Command).Setup (Config, Context); end Setup; begin Command_Drivers.Driver.Add_Command ("setup", -("start the web server and setup the application"), Command'Access); end AWA.Commands.Setup;
----------------------------------------------------------------------- -- awa-commands-setup -- Setup command to start and configure the application -- Copyright (C) 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 AWA.Applications; with AWA.Setup.Applications; with Servlet.Core; package body AWA.Commands.Setup is use AWA.Applications; package Command_Drivers renames Start_Command.Command_Drivers; overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); procedure Find_Application (Name : in String); procedure Enable_Application (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; procedure Find_Application (Name : in String) is procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin App.Disable; if URI (URI'First + 1 .. URI'Last) = Name then if App.all in Application'Class then Count := Count + 1; end if; end if; end Find; begin Command_Drivers.WS.Iterate (Find'Access); end Find_Application; procedure Enable_Application (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is pragma Unreferenced (URI); begin App.Enable; App.Start; end Enable_Application; S : aliased AWA.Setup.Applications.Application; begin if Args.Get_Count /= 1 then Context.Console.Notice (N_ERROR, -("Missing application name")); return; end if; declare Name : constant String := Args.Get_Argument (1); begin Find_Application (Name); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Command.Configure_Server (Context); Command.Start_Server (Context); S.Setup (Name, Command_Drivers.WS); Command.Configure_Applications (Context); S.Status.Set (AWA.Setup.Applications.READY); delay 2.0; Command_Drivers.WS.Remove_Application (S'Unchecked_Access); Command_Drivers.WS.Iterate (Enable_Application'Access); Command.Wait_Server (Context); end; end Execute; -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin Start_Command.Command_Type (Command).Setup (Config, Context); end Setup; begin Command_Drivers.Driver.Add_Command ("setup", -("start the web server and setup the application"), Command'Access); end AWA.Commands.Setup;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9c2e80d413567c7d2b4f9c6f4a5221688243f676
awa/plugins/awa-wikis/src/awa-wikis-previews.adb
awa/plugins/awa-wikis/src/awa-wikis-previews.adb
----------------------------------------------------------------------- -- awa-wikis-previews -- Wiki preview management -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Files; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Texts; with ADO; with EL.Contexts.TLS; with ASF.Servlets; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with AWA.Applications; with AWA.Services.Contexts; with AWA.Modules.Get; package body AWA.Wikis.Previews is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Wikis.Preview"); -- ------------------------------ -- The worker procedure that performs the preview job. -- ------------------------------ procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Previewer : constant Preview_Module_Access := Get_Preview_Module; begin Previewer.Do_Preview_Job (Job); end Preview_Worker; -- ------------------------------ -- Initialize the wikis module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Preview_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the wiki preview module"); 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 Preview_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Template := Plugin.Get_Config (PARAM_PREVIEW_TEMPLATE); Plugin.Command := Plugin.Get_Config (PARAM_PREVIEW_COMMAND); Plugin.Html := Plugin.Get_Config (PARAM_PREVIEW_HTML); Plugin.Add_Listener (AWA.Wikis.Modules.NAME, Plugin'Unchecked_Access); Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; Plugin.Job_Module.Register (Definition => Preview_Job_Definition.Factory); end Configure; -- ------------------------------ -- Execute the preview job and make the thumbnail preview. The page is first rendered in -- an HTML text file and the preview is rendered by using an external command. -- ------------------------------ procedure Do_Preview_Job (Plugin : in Preview_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is pragma Unreferenced (Job); use Util.Beans.Objects; Ctx : constant EL.Contexts.ELContext_Access := EL.Contexts.TLS.Current; Template : constant String := To_String (Plugin.Template.Get_Value (Ctx.all)); Command : constant String := To_String (Plugin.Command.Get_Value (Ctx.all)); Html_File : constant String := To_String (Plugin.Html.Get_Value (Ctx.all)); begin Log.Info ("Preview {0} with {1}", Template, Command); declare Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Dispatcher : constant ASF.Servlets.Request_Dispatcher := Plugin.Get_Application.Get_Request_Dispatcher (Template); Result : Ada.Strings.Unbounded.Unbounded_String; begin Req.Set_Request_URI (Template); Req.Set_Method ("GET"); ASF.Servlets.Forward (Dispatcher, Req, Reply); Reply.Read_Content (Result); Util.Files.Write_File (Html_File, Result); end; declare Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Input : Util.Streams.Texts.Reader_Stream; begin Log.Info ("Running preview command {0}", Command); Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Line, False); Log.Info ("Received: {0}", Line); end; end loop; Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Do_Preview_Job; -- ------------------------------ -- Create a preview job and schedule the job to generate a new thumbnail preview for the page. -- ------------------------------ procedure Make_Preview_Job (Plugin : in Preview_Module; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is pragma Unreferenced (Plugin); J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("wiki_space_id", Page.Get_Wiki); J.Set_Parameter ("wiki_page_id", Page); J.Schedule (Preview_Job_Definition.Factory.all); end Make_Preview_Job; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page. -- ------------------------------ overriding procedure On_Create (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page. -- ------------------------------ overriding procedure On_Update (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page. -- ------------------------------ overriding procedure On_Delete (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Delete; -- ------------------------------ -- Get the preview module instance associated with the current application. -- ------------------------------ function Get_Preview_Module return Preview_Module_Access is function Get is new AWA.Modules.Get (Preview_Module, Preview_Module_Access, NAME); begin return Get; end Get_Preview_Module; end AWA.Wikis.Previews;
----------------------------------------------------------------------- -- awa-wikis-previews -- Wiki preview management -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Files; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Texts; with ADO; with EL.Contexts.TLS; with ASF.Servlets; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with AWA.Applications; with AWA.Services.Contexts; with AWA.Modules.Get; package body AWA.Wikis.Previews is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Wikis.Preview"); -- ------------------------------ -- The worker procedure that performs the preview job. -- ------------------------------ procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Previewer : constant Preview_Module_Access := Get_Preview_Module; begin Previewer.Do_Preview_Job (Job); end Preview_Worker; -- ------------------------------ -- Initialize the wikis module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Preview_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the wiki preview module"); 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 Preview_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Template := Plugin.Get_Config (PARAM_PREVIEW_TEMPLATE); Plugin.Command := Plugin.Get_Config (PARAM_PREVIEW_COMMAND); Plugin.Html := Plugin.Get_Config (PARAM_PREVIEW_HTML); Plugin.Add_Listener (AWA.Wikis.Modules.NAME, Plugin'Unchecked_Access); Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; Plugin.Job_Module.Register (Definition => Preview_Job_Definition.Factory); end Configure; -- ------------------------------ -- Execute the preview job and make the thumbnail preview. The page is first rendered in -- an HTML text file and the preview is rendered by using an external command. -- ------------------------------ procedure Do_Preview_Job (Plugin : in Preview_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is pragma Unreferenced (Job); use Util.Beans.Objects; Ctx : constant EL.Contexts.ELContext_Access := EL.Contexts.TLS.Current; Template : constant String := To_String (Plugin.Template.Get_Value (Ctx.all)); Command : constant String := To_String (Plugin.Command.Get_Value (Ctx.all)); Html_File : constant String := To_String (Plugin.Html.Get_Value (Ctx.all)); begin Log.Info ("Preview {0} with {1}", Template, Command); declare Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Dispatcher : constant ASF.Servlets.Request_Dispatcher := Plugin.Get_Application.Get_Request_Dispatcher (Template); Result : Ada.Strings.Unbounded.Unbounded_String; begin Req.Set_Request_URI (Template); Req.Set_Method ("GET"); ASF.Servlets.Forward (Dispatcher, Req, Reply); Reply.Read_Content (Result); Util.Files.Write_File (Html_File, Result); end; declare Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Input : Util.Streams.Texts.Reader_Stream; begin Log.Info ("Running preview command {0}", Command); Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Line, False); Log.Info ("Received: {0}", Line); end; end loop; Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Do_Preview_Job; -- ------------------------------ -- Create a preview job and schedule the job to generate a new thumbnail preview for the page. -- ------------------------------ procedure Make_Preview_Job (Plugin : in Preview_Module; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is pragma Unreferenced (Plugin); J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("wiki_space_id", Page.Get_Wiki); J.Set_Parameter ("wiki_page_id", Page); J.Schedule (Preview_Job_Definition.Factory.all); end Make_Preview_Job; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page. -- ------------------------------ overriding procedure On_Create (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page. -- ------------------------------ overriding procedure On_Update (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page. -- ------------------------------ overriding procedure On_Delete (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Delete; -- ------------------------------ -- Get the preview module instance associated with the current application. -- ------------------------------ function Get_Preview_Module return Preview_Module_Access is function Get is new AWA.Modules.Get (Preview_Module, Preview_Module_Access, NAME); begin return Get; end Get_Preview_Module; end AWA.Wikis.Previews;
Update initialization of input reader stream
Update initialization of input reader stream
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
19aed162fe1bfec30c9d300e1e9281610a614afb
awa/regtests/awa-tests.adb
awa/regtests/awa-tests.adb
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Drivers; with ASF.Server.Web; with ASF.Navigations; with ASF.Server.Tests; with ASF.Tests; with AWA.Users.Module; with AWA.Mail.Module; with AWA.Applications; package body AWA.Tests is App : AWA.Applications.Application_Access := null; Users : aliased AWA.Users.Module.User_Module; -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager) is use AWA.Applications; begin ADO.Drivers.Initialize (Props); App := new AWA.Applications.Application; ASF.Tests.Initialize (Props, App.all'Access); declare Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler; Users : AWA.Users.Module.User_Module_Access := AWA.Tests.Users'Access; begin Register (App => App.all'Access, Name => AWA.Users.Module.NAME, URI => "user", Module => Users.all'Access); Register (App => App.all'Access, Name => "mail", URI => "mail", Module => AWA.Mail.Module.Instance.all'Access); Nav.Add_Navigation_Case (From => "/users/login.xhtml", To => "/users/main.xhtml", Outcome => "success"); Nav.Add_Navigation_Case (From => "/users/register.xhtml", To => "/users/registration-sent.xhtml", Outcome => "success"); -- if Props.Exists ("test.server") then -- declare -- WS : ASF.Server.Web.AWS_Container; -- begin -- WS.Register_Application ("/awa", App.all'Access); -- -- WS.Start; -- delay 600.0; -- end; -- end if; ASF.Server.Tests.Set_Context (App.all'Access); end; end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return App; end Get_Application; end AWA.Tests;
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Drivers; with ASF.Server.Web; with ASF.Navigations; with ASF.Server.Tests; with ASF.Tests; with AWA.Users.Module; with AWA.Mail.Module; with AWA.Applications; with AWA.Services.Filters; package body AWA.Tests is App : AWA.Applications.Application_Access := null; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Users : aliased AWA.Users.Module.User_Module; -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager) is use AWA.Applications; begin ADO.Drivers.Initialize (Props); App := new AWA.Applications.Application; ASF.Tests.Initialize (Props, App.all'Access); App.Add_Filter ("service", Service_Filter'Access); App.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); declare Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler; Users : AWA.Users.Module.User_Module_Access := AWA.Tests.Users'Access; begin Register (App => App.all'Access, Name => AWA.Users.Module.NAME, URI => "user", Module => Users.all'Access); Register (App => App.all'Access, Name => "mail", URI => "mail", Module => AWA.Mail.Module.Instance.all'Access); Nav.Add_Navigation_Case (From => "/users/login.xhtml", To => "/users/main.xhtml", Outcome => "success"); Nav.Add_Navigation_Case (From => "/users/register.xhtml", To => "/users/registration-sent.xhtml", Outcome => "success"); -- if Props.Exists ("test.server") then -- declare -- WS : ASF.Server.Web.AWS_Container; -- begin -- WS.Register_Application ("/awa", App.all'Access); -- -- WS.Start; -- delay 600.0; -- end; -- end if; ASF.Server.Tests.Set_Context (App.all'Access); end; end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return App; end Get_Application; end AWA.Tests;
Add the service filter to setup the service context when simulating a web request
Add the service filter to setup the service context when simulating a web request
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
94cd7b9cdf0b0f522484d62e997119f2d7ba5f08
src/asf-components-ajax-includes.adb
src/asf-components-ajax-includes.adb
----------------------------------------------------------------------- -- components-ajax-includes -- AJAX Include component -- 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 ASF.Applications.Main; with ASF.Applications.Views; with ASF.Components.Root; with ASF.Contexts.Writer; package body ASF.Components.Ajax.Includes is -- ------------------------------ -- Get the HTML layout that must be used for the include container. -- The default layout is a "div". -- Returns "div", "span", "pre", "b". -- ------------------------------ function Get_Layout (UI : in UIInclude; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Layout : constant String := UI.Get_Attribute (Name => LAYOUT_ATTR_NAME, Context => Context, Default => "div"); begin if Layout = "div" or Layout = "span" or Layout = "pre" or Layout = "b" then return Layout; else return "div"; end if; end Get_Layout; -- ------------------------------ -- The included XHTML file is rendered according to the <b>async</b> attribute: -- -- When <b>async</b> is false, render the specified XHTML file in such a way that inner -- forms will be posted on the included view. -- -- When <b>async</b> is true, trigger an AJAX call to include the specified -- XHTML view when the page is loaded. -- -- -- ------------------------------ overriding procedure Encode_Children (UI : in UIInclude; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application; View_Handler : constant access ASF.Applications.Views.View_Handler'Class := App.Get_View_Handler; Id : constant Ada.Strings.Unbounded.Unbounded_String := UI.Get_Client_Id; Layout : constant String := UIInclude'Class (UI).Get_Layout (Context); Async : constant Boolean := UI.Get_Attribute (Name => ASYNC_ATTR_NAME, Context => Context, Default => False); Page : constant String := UI.Get_Attribute (Name => SRC_ATTR_NAME, Context => Context, Default => ""); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element (Layout); UI.Render_Attributes (Context, Writer); -- In Async mode, generate the javascript code to trigger the async update of -- the generated div/span. if Async then Writer.Queue_Script ("ASF.Update("""); Writer.Queue_Script (Id); Writer.Queue_Script (""", """); Writer.Queue_Script (View_Handler.Get_Action_URL (Context, Page)); Writer.Queue_Script (""");"); else -- Include the view content as if the user fetched the patch. This has almost the -- same final result except that the inner content is returned now and not by -- another async http GET request. declare View : constant ASF.Components.Root.UIViewRoot := Context.Get_View_Root; Include_View : ASF.Components.Root.UIViewRoot; Is_Ajax : constant Boolean := Context.Is_Ajax_Request; Content_Type : constant String := Context.Get_Response.Get_Content_Type; begin Context.Set_Ajax_Request (True); View_Handler.Restore_View (Page, Context, Include_View); Context.Set_View_Root (Include_View); View_Handler.Render_View (Context, Include_View); Context.Get_Response.Set_Content_Type (Content_Type); Context.Set_View_Root (View); Context.Set_Ajax_Request (Is_Ajax); exception when others => Context.Get_Response.Set_Content_Type (Content_Type); Context.Set_View_Root (View); Context.Set_Ajax_Request (Is_Ajax); raise; end; end if; Writer.End_Element (Layout); end; end Encode_Children; end ASF.Components.Ajax.Includes;
----------------------------------------------------------------------- -- components-ajax-includes -- AJAX Include component -- 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 ASF.Applications.Main; with ASF.Applications.Views; with ASF.Components.Root; with ASF.Contexts.Writer; package body ASF.Components.Ajax.Includes is -- ------------------------------ -- Get the HTML layout that must be used for the include container. -- The default layout is a "div". -- Returns "div", "span", "pre", "b". -- ------------------------------ function Get_Layout (UI : in UIInclude; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Layout : constant String := UI.Get_Attribute (Name => LAYOUT_ATTR_NAME, Context => Context, Default => "div"); begin if Layout = "div" or Layout = "span" or Layout = "pre" or Layout = "b" then return Layout; else return "div"; end if; end Get_Layout; -- ------------------------------ -- The included XHTML file is rendered according to the <b>async</b> attribute: -- -- When <b>async</b> is false, render the specified XHTML file in such a way that inner -- forms will be posted on the included view. -- -- When <b>async</b> is true, trigger an AJAX call to include the specified -- XHTML view when the page is loaded. -- -- -- ------------------------------ overriding procedure Encode_Children (UI : in UIInclude; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application; View_Handler : constant access ASF.Applications.Views.View_Handler'Class := App.Get_View_Handler; Id : constant Ada.Strings.Unbounded.Unbounded_String := UI.Get_Client_Id; Layout : constant String := UIInclude'Class (UI).Get_Layout (Context); Async : constant Boolean := UI.Get_Attribute (Name => ASYNC_ATTR_NAME, Context => Context, Default => False); Page : constant String := UI.Get_Attribute (Name => SRC_ATTR_NAME, Context => Context, Default => ""); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element (Layout); UI.Render_Attributes (Context, Writer); -- In Async mode, generate the javascript code to trigger the async update of -- the generated div/span. if Async then Writer.Write_Attribute ("id", Id); Writer.Queue_Script ("ASF.Update(null,"""); Writer.Queue_Script (View_Handler.Get_Action_URL (Context, Page)); Writer.Queue_Script (""", ""#"); Writer.Queue_Script (Id); Writer.Queue_Script (""");"); else -- Include the view content as if the user fetched the patch. This has almost the -- same final result except that the inner content is returned now and not by -- another async http GET request. declare View : constant ASF.Components.Root.UIViewRoot := Context.Get_View_Root; Include_View : ASF.Components.Root.UIViewRoot; Is_Ajax : constant Boolean := Context.Is_Ajax_Request; Content_Type : constant String := Context.Get_Response.Get_Content_Type; begin Context.Set_Ajax_Request (True); View_Handler.Restore_View (Page, Context, Include_View); Context.Set_View_Root (Include_View); View_Handler.Render_View (Context, Include_View); Context.Get_Response.Set_Content_Type (Content_Type); Context.Set_View_Root (View); Context.Set_Ajax_Request (Is_Ajax); exception when others => Context.Get_Response.Set_Content_Type (Content_Type); Context.Set_View_Root (View); Context.Set_Ajax_Request (Is_Ajax); raise; end; end if; Writer.End_Element (Layout); end; end Encode_Children; end ASF.Components.Ajax.Includes;
Fix generation of javascript when rendering an ajax include in async mode
Fix generation of javascript when rendering an ajax include in async mode
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
3e153bc82647246245361025551d62050fbe78b4
src/sys/streams/util-streams-buffered-encoders.adb
src/sys/streams/util-streams-buffered-encoders.adb
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Streams.Buffered.Encoders is -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Encoder_Stream; Output : access Output_Stream'Class; Size : in Positive) is begin Util.Streams.Buffered.Output_Buffer_Stream (Stream).Initialize (Output, Size); end Initialize; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Encoder_Stream) is begin Stream.Flush; Stream.Output.Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Encoder_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First; Last_Encoded : Ada.Streams.Stream_Element_Offset; Last_Pos : Ada.Streams.Stream_Element_Offset; begin while First_Encoded <= Buffer'Last loop Stream.Transform.Transform (Data => Buffer (First_Encoded .. Buffer'Last), Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last => Last_Pos, Encoded => Last_Encoded); if Last_Encoded < Buffer'Last then Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Write_Pos := Stream.Buffer'First; else Stream.Write_Pos := Last_Pos + 1; end if; First_Encoded := Last_Encoded + 1; end loop; end Write; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Encoder_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset := Stream.Write_Pos - 1; begin if not Stream.Flushed then Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last_Pos); Stream.Write_Pos := Last_Pos + 1; Output_Buffer_Stream (Stream).Flush; Stream.Flushed := True; end if; end Flush; overriding procedure Finalize (Stream : in out Encoder_Stream) is begin if not Stream.Flushed then Stream.Flush; end if; Output_Buffer_Stream (Stream).Finalize; end Finalize; end Util.Streams.Buffered.Encoders;
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- Copyright (C) 2017, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Streams.Buffered.Encoders is -- ----------------------- -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ----------------------- procedure Initialize (Stream : in out Encoder_Stream; Size : in Positive) is begin Buffer_Stream (Stream).Initialize (Size); Stream.No_Flush := True; end Initialize; -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- -- overriding procedure Produces (Stream : in out Encoder_Stream; Output : access Output_Stream'Class; Size : in Positive) is begin Stream.Initialize (Size); Stream.Output := Output; Stream.No_Flush := False; end Produces; -- ----------------------- -- Initialize the stream to read the given streams. -- ----------------------- procedure Consumes (Stream : in out Encoder_Stream; Input : access Input_Stream'Class; Size : in Positive) is begin Stream.Initialize (Size); Stream.Input := Input; end Consumes; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Encoder_Stream) is begin Stream.Flush; if Stream.Output /= null then Stream.Output.Close; end if; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Encoder_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First; Last_Encoded : Ada.Streams.Stream_Element_Offset; Last_Pos : Ada.Streams.Stream_Element_Offset; begin while First_Encoded <= Buffer'Last loop Stream.Transform.Transform (Data => Buffer (First_Encoded .. Buffer'Last), Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last => Last_Pos, Encoded => Last_Encoded); if Last_Encoded < Buffer'Last or else Last_Pos = Stream.Buffer'Last then Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Write_Pos := Stream.Buffer'First; else Stream.Write_Pos := Last_Pos + 1; end if; First_Encoded := Last_Encoded + 1; end loop; end Write; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Encoder_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- `last` the position of the last byte read. -- ----------------------- overriding procedure Read (Stream : in out Encoder_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Last_Decoded : Ada.Streams.Stream_Element_Offset; Last_Pos : Ada.Streams.Stream_Element_Offset; begin while Start <= Into'Last loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; if Avail <= 0 then Last := Start - 1; Stream.Transform.Finish (Into => Into (Start .. Into'Last), Last => Last); return; end if; end if; Stream.Transform.Transform (Data => Stream.Buffer (Pos .. Pos + Avail - 1), Into => Into (Start .. Into'Last), Last => Last_Pos, Encoded => Last_Decoded); Stream.Read_Pos := Last_Decoded + 1; Start := Last_Pos + 1; exit when Stream.Read_Pos = Pos; Pos := Stream.Read_Pos; end loop; Last := Start - 1; end Read; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Encoder_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset := Stream.Write_Pos - 1; begin if not Stream.Flushed and then Stream.Buffer /= null and then Stream.Write_Pos >= Stream.Buffer'First then Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last_Pos); Stream.Write_Pos := Last_Pos + 1; if not Stream.No_Flush then if Stream.Write_Pos > 1 then if Stream.Output /= null then Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); end if; Stream.Write_Pos := 1; end if; if Stream.Output /= null then Stream.Output.Flush; end if; end if; Stream.Flushed := True; end if; end Flush; overriding procedure Finalize (Stream : in out Encoder_Stream) is begin if not Stream.Flushed and then Stream.Buffer /= null then Stream.Flush; end if; Buffer_Stream (Stream).Finalize; end Finalize; end Util.Streams.Buffered.Encoders;
Refactor the Util.Stream.Buffered stream - allow to use the target stream with Read (pull model) and Write (push model)
Refactor the Util.Stream.Buffered stream - allow to use the target stream with Read (pull model) and Write (push model)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
52adf4ec9fd8632a1d9855bddae0c0d7c1f15730
src/gen-artifacts-docs-markdown.adb
src/gen-artifacts-docs-markdown.adb
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 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.Strings.Fixed; with Util.Strings; with Util.Log.Loggers; package body Gen.Artifacts.Docs.Markdown is function Has_Scheme (Link : in String) return Boolean; function Is_Image (Link : in String) return Boolean; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Docs.Mark"); -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end if; end Start_Document; -- ------------------------------ -- Return True if the link has either a http:// or a https:// scheme. -- ------------------------------ function Has_Scheme (Link : in String) return Boolean is begin if Link'Length < 8 then return False; elsif Link (Link'First .. Link'First + 6) = "http://" then return True; elsif Link (Link'First .. Link'First + 7) = "https://" then return True; else return False; end if; end Has_Scheme; function Is_Image (Link : in String) return Boolean is begin if Link'Length < 4 then return False; elsif Link (Link'Last - 3 .. Link'Last) = ".png" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then return True; else Log.Info ("Link {0} not an image", Link); return False; end if; end Is_Image; -- ------------------------------ -- Write a line doing some link transformation for Markdown. -- ------------------------------ procedure Write_Text (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is pragma Unreferenced (Formatter); Pos : Natural; Start : Natural := Text'First; End_Pos : Natural; Last_Pos : Natural; begin -- Transform links -- [Link] -> [[Link]] -- [Link Title] -> [[Title|Link]] -- -- Do not change the following links: -- [[Link|Title]] loop Pos := Util.Strings.Index (Text, '[', Start); if Pos = 0 or else Pos = Text'Last then Ada.Text_IO.Put (File, Text (Start .. Text'Last)); return; end if; Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); if Pos - 1 >= Text'First and then (Text (Pos - 1) = '\' or Text (Pos - 1) = '`') then Ada.Text_IO.Put (File, "["); Start := Pos + 1; -- Parse a markdown link format. elsif Text (Pos + 1) = '[' then Start := Pos + 2; Pos := Util.Strings.Index (Text, ']', Pos + 2); if Pos = 0 then if Is_Image (Text (Start .. Text'Last)) then Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); else Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); end if; return; end if; if Is_Image (Text (Start .. Pos - 1)) then Ada.Text_IO.Put (File, "![]("); Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); Ada.Text_IO.Put (File, ")"); Start := Pos + 2; else Ada.Text_IO.Put (File, Text (Start .. Pos)); Start := Pos + 1; end if; else Pos := Pos + 1; End_Pos := Pos; while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop End_Pos := End_Pos + 1; end loop; Last_Pos := End_Pos; while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop Last_Pos := Last_Pos + 1; end loop; if Is_Image (Text (Pos .. Last_Pos - 1)) then Ada.Text_IO.Put (File, "!["); -- Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1)); Ada.Text_IO.Put (File, ")"); elsif Is_Image (Text (Pos .. End_Pos)) then Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "!["); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, ")"); elsif Has_Scheme (Text (Pos .. End_Pos)) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "("); Ada.Text_IO.Put (File, Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both)); Ada.Text_IO.Put (File, ")"); else Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "[["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "|"); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]"); end if; Start := Last_Pos + 1; end if; end loop; end Write_Text; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; if Formatter.Mode = L_START_CODE and then Line'Length > 2 and then Line (Line'First .. Line'First + 1) = " " then Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last)); elsif Formatter.Mode = L_TEXT then Formatter.Write_Text (File, Line); Ada.Text_IO.New_Line (File); else Ada.Text_IO.Put_Line (File, Line); end if; end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; Formatter.Mode := Line.Kind; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "```Ada"); when L_END_CODE => Formatter.Mode := L_TEXT; Formatter.Write_Line (File, "```"); when L_TEXT => Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "# " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_2 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "## " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_3 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "### " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_4 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "#### " & Line.Content); Formatter.Mode := L_TEXT; when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter); begin Ada.Text_IO.New_Line (File); if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end if; end Finish_Document; end Gen.Artifacts.Docs.Markdown;
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 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.Strings.Fixed; with Ada.Strings.Maps; with Util.Strings; with Util.Log.Loggers; package body Gen.Artifacts.Docs.Markdown is use type Ada.Strings.Maps.Character_Set; function Has_Scheme (Link : in String) return Boolean; function Is_Image (Link : in String) return Boolean; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Docs.Mark"); Marker : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (" .,;:!?") or Ada.Strings.Maps.To_Set (ASCII.HT) or Ada.Strings.Maps.To_Set (ASCII.VT) or Ada.Strings.Maps.To_Set (ASCII.CR) or Ada.Strings.Maps.To_Set (ASCII.LF); -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end if; end Start_Document; -- ------------------------------ -- Return True if the link has either a http:// or a https:// scheme. -- ------------------------------ function Has_Scheme (Link : in String) return Boolean is begin if Link'Length < 8 then return False; elsif Link (Link'First .. Link'First + 6) = "http://" then return True; elsif Link (Link'First .. Link'First + 7) = "https://" then return True; else return False; end if; end Has_Scheme; function Is_Image (Link : in String) return Boolean is begin if Link'Length < 4 then return False; elsif Link (Link'Last - 3 .. Link'Last) = ".png" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then return True; else Log.Info ("Link {0} not an image", Link); return False; end if; end Is_Image; procedure Write_Text_Auto_Links (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is Start : Natural := Text'First; Last : Natural := Text'Last; Link : Util.Strings.Maps.Cursor; Pos : Natural; begin Log.Debug ("Auto link |{0}|", Text); loop -- Emit spaces at beginning of line or words. while Start <= Text'Last and then Ada.Strings.Maps.Is_In (Text (Start), Marker) loop Ada.Text_IO.Put (File, Text (Start)); Start := Start + 1; end loop; exit when Start > Text'Last; -- Find a possible link. Link := Formatter.Links.Find (Text (Start .. Last)); if Util.Strings.Maps.Has_Element (Link) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (Start .. Last)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Util.Strings.Maps.Element (Link)); Ada.Text_IO.Put (File, ")"); Start := Last + 1; Last := Text'Last; else Pos := Ada.Strings.Fixed.Index (Text (Start .. Last), Marker, Going => Ada.Strings.Backward); if Pos = 0 then Ada.Text_IO.Put (File, Text (Start .. Last)); Start := Last + 1; Last := Text'Last; else Last := Pos - 1; -- Skip spaces at end of words for the search. while Last > Start and then Ada.Strings.Maps.Is_In (Text (Last), Marker) loop Last := Last - 1; end loop; end if; end if; end loop; end Write_Text_Auto_Links; -- ------------------------------ -- Write a line doing some link transformation for Markdown. -- ------------------------------ procedure Write_Text (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is Pos : Natural; Start : Natural := Text'First; End_Pos : Natural; Last_Pos : Natural; begin -- Transform links -- [Link] -> [[Link]] -- [Link Title] -> [[Title|Link]] -- -- Do not change the following links: -- [[Link|Title]] loop Pos := Util.Strings.Index (Text, '[', Start); if Pos = 0 or else Pos = Text'Last then Formatter.Write_Text_Auto_Links (File, Text (Start .. Text'Last)); return; end if; Formatter.Write_Text_Auto_Links (File, Text (Start .. Pos - 1)); if Pos - 1 >= Text'First and then (Text (Pos - 1) = '\' or Text (Pos - 1) = '`') then Ada.Text_IO.Put (File, "["); Start := Pos + 1; -- Parse a markdown link format. elsif Text (Pos + 1) = '[' then Start := Pos + 2; Pos := Util.Strings.Index (Text, ']', Pos + 2); if Pos = 0 then if Is_Image (Text (Start .. Text'Last)) then Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); else Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); end if; return; end if; if Is_Image (Text (Start .. Pos - 1)) then Ada.Text_IO.Put (File, "![]("); Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); Ada.Text_IO.Put (File, ")"); Start := Pos + 2; else Ada.Text_IO.Put (File, Text (Start .. Pos)); Start := Pos + 1; end if; else Pos := Pos + 1; End_Pos := Pos; while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop End_Pos := End_Pos + 1; end loop; Last_Pos := End_Pos; while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop Last_Pos := Last_Pos + 1; end loop; if Is_Image (Text (Pos .. Last_Pos - 1)) then Ada.Text_IO.Put (File, "!["); -- Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1)); Ada.Text_IO.Put (File, ")"); elsif Is_Image (Text (Pos .. End_Pos)) then Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "!["); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, ")"); elsif Has_Scheme (Text (Pos .. End_Pos)) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "("); Ada.Text_IO.Put (File, Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both)); Ada.Text_IO.Put (File, ")"); else Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "[["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "|"); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]"); end if; Start := Last_Pos + 1; end if; end loop; end Write_Text; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; if Formatter.Mode = L_START_CODE and then Line'Length > 2 and then Line (Line'First .. Line'First + 1) = " " then Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last)); elsif Formatter.Mode = L_TEXT then Formatter.Write_Text (File, Line); Ada.Text_IO.New_Line (File); else Ada.Text_IO.Put_Line (File, Line); end if; end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; Formatter.Mode := Line.Kind; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "```Ada"); when L_END_CODE => Formatter.Mode := L_TEXT; Formatter.Write_Line (File, "```"); when L_TEXT => Formatter.Mode := L_TEXT; Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "# " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_2 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "## " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_3 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "### " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_4 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "#### " & Line.Content); Formatter.Mode := L_TEXT; when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter); begin Ada.Text_IO.New_Line (File); if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end if; end Finish_Document; end Gen.Artifacts.Docs.Markdown;
Implement the Write_Text_Auto_Links to replace some text strings with a link based on the link file that was loaded.
Implement the Write_Text_Auto_Links to replace some text strings with a link based on the link file that was loaded.
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
22286b2c05b99b00be70c28f266d5a3ca3ca4c51
tools/druss-commands-status.ads
tools/druss-commands-status.ads
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Util.Properties; with Util.Commands; with Druss.Gateways; package Druss.Commands.Status is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type); -- Execute a status command to report information about the Bbox. 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.Status;
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- 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.Status is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type); -- Execute a status command to report information about the Bbox. 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.Status;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/bbox-ada-api
77536b1e8a964dfa3830f65d2b5635e8d411ebe1
mat/src/mat-readers-marshaller.ads
mat/src/mat-readers-marshaller.ads
----------------------------------------------------------------------- -- Marshaller -- Marshalling of data in communication buffer -- 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 System; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Buffer_Ptr) return String; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type; function Get_Target_Size is new Get_Target_Value (MAT.Types.Target_Size); function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- Marshaller -- Marshalling of data in communication buffer -- 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 System; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Buffer_Ptr) return String; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type; -- -- function Get_Target_Size is new Get_Target_Value (MAT.Types.Target_Size); -- -- function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); -- -- function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); -- -- function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr; -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
Fix instantiation issue
Fix instantiation issue
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
668f22990980f475858c583dca524413942414a3
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. -- -- 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. -- -- <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. -- -- A <tt>Security_Context</tt> can be associated -- -- -- 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); -- ------------------------------ -- 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); -- ------------------------------ -- 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); 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. -- -- 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. -- -- <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. -- -- 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); -- ------------------------------ -- 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); -- ------------------------------ -- 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); 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;
Document how to set the roles on a security context
Document how to set the roles on a security context
Ada
apache-2.0
stcarrez/ada-security
1f475936ace84b9be731fb02b517d01eded25c3d
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management 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 Util.Log.Loggers; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with ADO.Sessions; with Ada.Calendar; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Stat_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.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); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Permissions.Services.Add_Permission (Session => DB, User => User, Entity => Blog); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- 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) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.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); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- 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) is pragma Unreferenced (Model); use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with ADO.Sessions; with Ada.Calendar; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Stat_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.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); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Permissions.Services.Add_Permission (Session => DB, User => User, Entity => Blog, Workspace => WS.Get_Id); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- 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) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.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); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- 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) is pragma Unreferenced (Model); use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; end AWA.Blogs.Modules;
Update the Add_Permission to indicate the workspace
Update the Add_Permission to indicate the workspace
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9f3d05eb6e2676f211cb9beba83a882fef789610
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Frames; with MAT.Clients; with Util.Events; with MAT.Memory.Events; package MAT.Memory.Clients is type Client_Memory is new MAT.Clients.ClientInfo with record Memory_Slots : Allocation_Map; Frames : MAT.Frames.Frame; Event_Channel : MAT.Memory.Events.Memory_Event_Channel.Channel; end record; type Client_Memory_Ref is access all Client_Memory'Class; -- procedure Create_Instance (Refs : in ClientInfo_Ref_Map); end MAT.Memory.Clients;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Frames; with Util.Events; with MAT.Memory.Events; package MAT.Memory.Targets is type Client_Memory is new MAT.Clients.ClientInfo with record Memory_Slots : Allocation_Map; Frames : MAT.Frames.Frame; Event_Channel : MAT.Memory.Events.Memory_Event_Channel.Channel; end record; type Client_Memory_Ref is access all Client_Memory'Class; -- procedure Create_Instance (Refs : in ClientInfo_Ref_Map); end MAT.Memory.Targets;
Rename package to MAT.Memory.Targets
Rename package to MAT.Memory.Targets
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e41ccea6e9415b3d5587ea0c684d839467352695
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- Append the text with the given format at end of the document. procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a link. procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Into : in out Document; Level : in Natural); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- Append the text with the given format at end of the document. procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a link. procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Into : in out Document; Level : in Natural); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
Declare Add_List_Item procedure
Declare Add_List_Item procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d81c2f6dd4884ea7e4b78ea726d9d099b338939b
mat/src/mat-commands.ads
mat/src/mat-commands.ads
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- 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 GNAT.Sockets; with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type'Class); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- 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 GNAT.Sockets; with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
Move the Interactive procedure in MAT.Targets
Move the Interactive procedure in MAT.Targets
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
016c1e29c48c9d177211f16e55f400aa7b863765
tools/druss-commands-status.adb
tools/druss-commands-status.adb
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Util.Properties; with Druss.Gateways; package body Druss.Commands.Status is use Ada.Text_IO; use Ada.Strings.Unbounded; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Refresh; Put (To_String (Gateway.Ip)); Set_Col (30); Put (Gateway.Wan.Get ("wan.internet.state", "?")); Set_Col (38); Put (Gateway.Wan.Get ("wan.ip.address", "?")); Set_Col (60); Put (Gateway.Device.Get ("device.numberofboots", "-")); Set_Col (68); Put (Gateway.Device.Get ("device.uptime", "-")); New_Line; end Box_Status; -- ------------------------------ -- Report wan status. -- ------------------------------ procedure Wan_Status (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Druss.Gateways.Iterate (Context.Gateways, Box_Status'Access); end Wan_Status; end Druss.Commands.Status;
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Strings.Unbounded; with Util.Properties; with Druss.Gateways; package body Druss.Commands.Status is use Ada.Text_IO; use Ada.Strings.Unbounded; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Refresh; Put (To_String (Gateway.Ip)); Set_Col (30); Put (Gateway.Wan.Get ("wan.internet.state", "?")); Set_Col (38); Put (Gateway.Wan.Get ("wan.ip.address", "?")); Set_Col (60); Put (Gateway.Device.Get ("device.numberofboots", "-")); Set_Col (68); Put (Gateway.Device.Get ("device.uptime", "-")); New_Line; end Box_Status; -- ------------------------------ -- Report wan status. -- ------------------------------ procedure Wan_Status (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Druss.Gateways.Iterate (Context.Gateways, Box_Status'Access); end Wan_Status; end Druss.Commands.Status;
Add with clause Ada.Strings.Unbounded
Add with clause Ada.Strings.Unbounded
Ada
apache-2.0
stcarrez/bbox-ada-api
e559ba3a1ce06485d252e8c20e2af051c4d46afa
boards/MicroBit/src/microbit-time.adb
boards/MicroBit/src/microbit-time.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with Interfaces; use Interfaces; with nRF51.Clock; with nRF51.Device; use nRF51.Device; with nRF51.RTC; use nRF51.RTC; with nRF51.Events; with nRF51.Interrupts; package body MicroBit.Time is package Clocks renames nRF51.Clock; Clock_Ms : Time_Ms := 0; Period_Ms : constant Time_Ms := 1; Subscribers : array (1 .. 10) of Tick_Callback := (others => null); procedure Initialize; procedure Update_Clock; procedure RTC1_IRQHandler; pragma Export (C, RTC1_IRQHandler, "RTC1_IRQHandler"); ---------------- -- Initialize -- ---------------- procedure Initialize is begin if not Clocks.Low_Freq_Running then Clocks.Set_Low_Freq_Source (Clocks.LFCLK_XTAL); Clocks.Start_Low_Freq; loop exit when Clocks.Low_Freq_Running; end loop; end if; Stop (RTC1); -- 1kHz Set_Prescaler (RTC1, 0); Set_Compare (RTC1, 0, 16); Enable_Event (RTC1, Compare_0_Event); nRF51.Events.Enable_Interrupt (nRF51.Events.RTC_1_COMPARE_0); nRF51.Interrupts.Enable (nRF51.Interrupts.RTC1_Interrupt); Start (RTC1); end Initialize; ------------------ -- Update_Clock -- ------------------ procedure Update_Clock is begin Clock_Ms := Clock_Ms + Period_Ms; end Update_Clock; --------------------- -- RTC1_IRQHandler -- --------------------- procedure RTC1_IRQHandler is begin Stop (RTC1); Clear (RTC1); Start (RTC1); nRF51.Events.Clear (nRF51.Events.RTC_1_COMPARE_0); Update_Clock; for Subs of Subscribers loop if Subs /= null then -- Call the subscriber Subs.all; end if; end loop; end RTC1_IRQHandler; ----------- -- Clock -- ----------- function Clock return Time_Ms is begin return Clock_Ms; end Clock; ----------------- -- Tick_Period -- ----------------- function Tick_Period return Time_Ms is begin return Period_Ms; end Tick_Period; -------------------- -- Tick_Subscribe -- -------------------- function Tick_Subscriber (Callback : not null Tick_Callback) return Boolean is begin for Subs of Subscribers loop if Subs = Callback then return True; end if; end loop; return False; end Tick_Subscriber; -------------------- -- Tick_Subscribe -- -------------------- function Tick_Subscribe (Callback : not null Tick_Callback) return Boolean is begin for Subs of Subscribers loop if Subs = null then Subs := Callback; return True; end if; end loop; return False; end Tick_Subscribe; ---------------------- -- Tick_Unsubscribe -- ---------------------- function Tick_Unsubscribe (Callback : not null Tick_Callback) return Boolean is begin for Subs of Subscribers loop if Subs = Callback then Subs := null; return True; end if; end loop; return False; end Tick_Unsubscribe; begin Initialize; end MicroBit.Time;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with Interfaces; use Interfaces; with nRF51.Clock; with nRF51.Device; use nRF51.Device; with nRF51.RTC; use nRF51.RTC; with nRF51.Events; with nRF51.Interrupts; package body MicroBit.Time is package Clocks renames nRF51.Clock; Clock_Ms : Time_Ms := 0; Period_Ms : constant Time_Ms := 1; Subscribers : array (1 .. 10) of Tick_Callback := (others => null); procedure Initialize; procedure Update_Clock; procedure RTC1_IRQHandler; pragma Export (C, RTC1_IRQHandler, "RTC1_IRQHandler"); ---------------- -- Initialize -- ---------------- procedure Initialize is begin if not Clocks.Low_Freq_Running then Clocks.Set_Low_Freq_Source (Clocks.LFCLK_XTAL); Clocks.Start_Low_Freq; loop exit when Clocks.Low_Freq_Running; end loop; end if; Stop (RTC1); -- 1kHz Set_Prescaler (RTC1, 0); Set_Compare (RTC1, 0, 32); Enable_Event (RTC1, Compare_0_Event); nRF51.Events.Enable_Interrupt (nRF51.Events.RTC_1_COMPARE_0); nRF51.Interrupts.Enable (nRF51.Interrupts.RTC1_Interrupt); Start (RTC1); end Initialize; ------------------ -- Update_Clock -- ------------------ procedure Update_Clock is begin Clock_Ms := Clock_Ms + Period_Ms; end Update_Clock; --------------------- -- RTC1_IRQHandler -- --------------------- procedure RTC1_IRQHandler is begin Stop (RTC1); Clear (RTC1); Start (RTC1); nRF51.Events.Clear (nRF51.Events.RTC_1_COMPARE_0); Update_Clock; for Subs of Subscribers loop if Subs /= null then -- Call the subscriber Subs.all; end if; end loop; end RTC1_IRQHandler; ----------- -- Clock -- ----------- function Clock return Time_Ms is begin return Clock_Ms; end Clock; ----------------- -- Tick_Period -- ----------------- function Tick_Period return Time_Ms is begin return Period_Ms; end Tick_Period; -------------------- -- Tick_Subscribe -- -------------------- function Tick_Subscriber (Callback : not null Tick_Callback) return Boolean is begin for Subs of Subscribers loop if Subs = Callback then return True; end if; end loop; return False; end Tick_Subscriber; -------------------- -- Tick_Subscribe -- -------------------- function Tick_Subscribe (Callback : not null Tick_Callback) return Boolean is begin for Subs of Subscribers loop if Subs = null then Subs := Callback; return True; end if; end loop; return False; end Tick_Subscribe; ---------------------- -- Tick_Unsubscribe -- ---------------------- function Tick_Unsubscribe (Callback : not null Tick_Callback) return Boolean is begin for Subs of Subscribers loop if Subs = Callback then Subs := null; return True; end if; end loop; return False; end Tick_Unsubscribe; begin Initialize; end MicroBit.Time;
Fix tick frequency
MicroBit: Fix tick frequency
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
a406409532572a7809fe225f6e558998ac00a97e
src/asf-components-html-text.adb
src/asf-components-html-text.adb
----------------------------------------------------------------------- -- html -- ASF HTML Components -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Unchecked_Deallocation; with EL.Objects; with ASF.Components.Core; with ASF.Utils; package body ASF.Components.Html.Text is use EL.Objects; TEXT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; LABEL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Get the local value of the component without evaluating -- the associated Value_Expression. -- ------------------------------ overriding function Get_Local_Value (UI : in UIOutput) return EL.Objects.Object is begin return UI.Value; end Get_Local_Value; -- ------------------------------ -- Get the value to write on the output. -- ------------------------------ overriding function Get_Value (UI : in UIOutput) return EL.Objects.Object is begin if not EL.Objects.Is_Null (UI.Value) then return UI.Value; else return UI.Get_Attribute (UI.Get_Context.all, "value"); end if; end Get_Value; -- ------------------------------ -- Set the value to write on the output. -- ------------------------------ overriding procedure Set_Value (UI : in out UIOutput; Value : in EL.Objects.Object) is begin UI.Value := Value; end Set_Value; -- ------------------------------ -- Get the converter that is registered on the component. -- ------------------------------ overriding function Get_Converter (UI : in UIOutput) return ASF.Converters.Converter_Access is begin return UI.Converter; end Get_Converter; -- ------------------------------ -- Set the converter to be used on the component. -- ------------------------------ overriding procedure Set_Converter (UI : in out UIOutput; Converter : in ASF.Converters.Converter_Access; Release : in Boolean := False) is use type ASF.Converters.Converter_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Converter'Class, Name => ASF.Converters.Converter_Access); begin if UI.Release_Converter then Free (UI.Converter); end if; if Converter = null then UI.Converter := null; UI.Release_Converter := False; else UI.Converter := Converter.all'Unchecked_Access; UI.Release_Converter := Release; end if; end Set_Converter; -- ------------------------------ -- Get the value of the component and apply the converter on it if there is one. -- ------------------------------ function Get_Formatted_Value (UI : in UIOutput; Context : in Faces_Context'Class) return String is Value : constant EL.Objects.Object := UIOutput'Class (UI).Get_Value; begin return UIOutput'Class (UI).Get_Formatted_Value (Value, Context); end Get_Formatted_Value; -- ------------------------------ -- Format the value by appling the To_String converter on it if there is one. -- ------------------------------ function Get_Formatted_Value (UI : in UIOutput; Value : in Util.Beans.Objects.Object; Context : in Contexts.Faces.Faces_Context'Class) return String is use type ASF.Converters.Converter_Access; begin if UI.Converter /= null then return UI.Converter.To_String (Context => Context, Component => UI, Value => Value); else declare Converter : constant access ASF.Converters.Converter'Class := UI.Get_Converter (Context); begin if Converter /= null then return Converter.To_String (Context => Context, Component => UI, Value => Value); elsif not Is_Null (Value) then return EL.Objects.To_String (Value); else return ""; end if; end; end if; -- If the converter raises an exception, report an error in the logs. -- At this stage, we know the value and we can report it in this log message. -- We must queue the exception in the context, so this is done later. exception when E : others => UI.Log_Error ("Error when converting value '{0}': {1}: {2}", Util.Beans.Objects.To_String (Value), Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E)); raise; end Get_Formatted_Value; procedure Write_Output (UI : in UIOutput; Context : in out Faces_Context'Class; Value : in String) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Escape : constant Object := UI.Get_Attribute (Context, "escape"); begin Writer.Start_Optional_Element ("span"); UI.Render_Attributes (Context, TEXT_ATTRIBUTE_NAMES, Writer); if Is_Null (Escape) or To_Boolean (Escape) then Writer.Write_Text (Value); else Writer.Write_Raw (Value); end if; Writer.End_Optional_Element ("span"); end Write_Output; procedure Encode_Begin (UI : in UIOutput; Context : in out Faces_Context'Class) is begin if UI.Is_Rendered (Context) then UI.Write_Output (Context => Context, Value => UIOutput'Class (UI).Get_Formatted_Value (Context)); end if; -- Queue any block converter exception that could be raised. exception when E : others => Context.Queue_Exception (E); end Encode_Begin; overriding procedure Finalize (UI : in out UIOutput) is begin UI.Set_Converter (null); UIHtmlComponent (UI).Finalize; end Finalize; -- ------------------------------ -- Label Component -- ------------------------------ procedure Encode_Begin (UI : in UIOutputLabel; Context : in out Faces_Context'Class) is Writer : Response_Writer_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.Start_Element ("label"); UI.Render_Attributes (Context, LABEL_ATTRIBUTE_NAMES, Writer); declare Value : Util.Beans.Objects.Object := UI.Get_Attribute (Name => "for", Context => Context); begin if not Util.Beans.Objects.Is_Null (Value) then Writer.Write_Attribute ("for", Value); end if; Value := UIOutputLabel'Class (UI).Get_Value; if not Util.Beans.Objects.Is_Null (Value) then declare S : constant String := UIOutputLabel'Class (UI).Get_Formatted_Value (Value, Context); begin if UI.Get_Attribute (Name => "escape", Context => Context, Default => True) then Writer.Write_Text (S); else Writer.Write_Raw (S); end if; end; end if; -- Queue and block any converter exception that could be raised. exception when E : others => Context.Queue_Exception (E); end; end if; end Encode_Begin; procedure Encode_End (UI : in UIOutputLabel; Context : in out Faces_Context'Class) is Writer : Response_Writer_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.End_Element ("label"); end if; end Encode_End; -- ------------------------------ -- OutputFormat Component -- ------------------------------ procedure Encode_Begin (UI : in UIOutputFormat; Context : in out Faces_Context'Class) is use ASF.Components.Core; use ASF.Utils; begin if not UI.Is_Rendered (Context) then return; end if; declare Params : constant UIParameter_Access_Array := Get_Parameters (UI); Values : ASF.Utils.Object_Array (Params'Range); Result : Ada.Strings.Unbounded.Unbounded_String; Fmt : constant String := EL.Objects.To_String (UI.Get_Value); begin -- Get the values associated with the parameters. for I in Params'Range loop Values (I) := Params (I).Get_Value (Context); end loop; Formats.Format (Fmt, Values, Result); UI.Write_Output (Context => Context, Value => To_String (Result)); end; end Encode_Begin; begin Utils.Set_Text_Attributes (TEXT_ATTRIBUTE_NAMES); Utils.Set_Text_Attributes (LABEL_ATTRIBUTE_NAMES); Utils.Set_Interactive_Attributes (LABEL_ATTRIBUTE_NAMES); end ASF.Components.Html.Text;
----------------------------------------------------------------------- -- html -- ASF HTML Components -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Unchecked_Deallocation; with EL.Objects; with ASF.Components.Core; with ASF.Utils; package body ASF.Components.Html.Text is use EL.Objects; TEXT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; LABEL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Get the local value of the component without evaluating -- the associated Value_Expression. -- ------------------------------ overriding function Get_Local_Value (UI : in UIOutput) return EL.Objects.Object is begin return UI.Value; end Get_Local_Value; -- ------------------------------ -- Get the value to write on the output. -- ------------------------------ overriding function Get_Value (UI : in UIOutput) return EL.Objects.Object is begin if not EL.Objects.Is_Null (UI.Value) then return UI.Value; else return UI.Get_Attribute (UI.Get_Context.all, "value"); end if; end Get_Value; -- ------------------------------ -- Set the value to write on the output. -- ------------------------------ overriding procedure Set_Value (UI : in out UIOutput; Value : in EL.Objects.Object) is begin UI.Value := Value; end Set_Value; -- ------------------------------ -- Get the converter that is registered on the component. -- ------------------------------ overriding function Get_Converter (UI : in UIOutput) return ASF.Converters.Converter_Access is begin return UI.Converter; end Get_Converter; -- ------------------------------ -- Set the converter to be used on the component. -- ------------------------------ overriding procedure Set_Converter (UI : in out UIOutput; Converter : in ASF.Converters.Converter_Access; Release : in Boolean := False) is use type ASF.Converters.Converter_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Converter'Class, Name => ASF.Converters.Converter_Access); begin if UI.Release_Converter then Free (UI.Converter); end if; if Converter = null then UI.Converter := null; UI.Release_Converter := False; else UI.Converter := Converter.all'Unchecked_Access; UI.Release_Converter := Release; end if; end Set_Converter; -- ------------------------------ -- Get the value of the component and apply the converter on it if there is one. -- ------------------------------ function Get_Formatted_Value (UI : in UIOutput; Context : in Faces_Context'Class) return String is Value : constant EL.Objects.Object := UIOutput'Class (UI).Get_Value; begin return UIOutput'Class (UI).Get_Formatted_Value (Value, Context); end Get_Formatted_Value; -- ------------------------------ -- Get the converter associated with the component -- ------------------------------ function Get_Converter (UI : in UIOutput; Context : in Faces_Context'Class) return access ASF.Converters.Converter'Class is use type ASF.Converters.Converter_Access; Result : ASF.Converters.Converter_Access := UIOutput'Class (UI).Get_Converter; begin if Result /= null then return Result; else declare Name : constant EL.Objects.Object := UIOutput'Class (UI).Get_Attribute (Name => CONVERTER_NAME, Context => Context); begin return Context.Get_Converter (Name); end; end if; end Get_Converter; -- ------------------------------ -- Format the value by appling the To_String converter on it if there is one. -- ------------------------------ function Get_Formatted_Value (UI : in UIOutput; Value : in Util.Beans.Objects.Object; Context : in Contexts.Faces.Faces_Context'Class) return String is use type ASF.Converters.Converter_Access; begin if UI.Converter /= null then return UI.Converter.To_String (Context => Context, Component => UI, Value => Value); else declare Converter : constant access ASF.Converters.Converter'Class := UI.Get_Converter (Context); begin if Converter /= null then return Converter.To_String (Context => Context, Component => UI, Value => Value); elsif not Is_Null (Value) then return EL.Objects.To_String (Value); else return ""; end if; end; end if; -- If the converter raises an exception, report an error in the logs. -- At this stage, we know the value and we can report it in this log message. -- We must queue the exception in the context, so this is done later. exception when E : others => UI.Log_Error ("Error when converting value '{0}': {1}: {2}", Util.Beans.Objects.To_String (Value), Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E)); raise; end Get_Formatted_Value; procedure Write_Output (UI : in UIOutput; Context : in out Faces_Context'Class; Value : in String) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Escape : constant Object := UI.Get_Attribute (Context, "escape"); begin Writer.Start_Optional_Element ("span"); UI.Render_Attributes (Context, TEXT_ATTRIBUTE_NAMES, Writer); if Is_Null (Escape) or To_Boolean (Escape) then Writer.Write_Text (Value); else Writer.Write_Raw (Value); end if; Writer.End_Optional_Element ("span"); end Write_Output; procedure Encode_Begin (UI : in UIOutput; Context : in out Faces_Context'Class) is begin if UI.Is_Rendered (Context) then UI.Write_Output (Context => Context, Value => UIOutput'Class (UI).Get_Formatted_Value (Context)); end if; -- Queue any block converter exception that could be raised. exception when E : others => Context.Queue_Exception (E); end Encode_Begin; overriding procedure Finalize (UI : in out UIOutput) is begin UI.Set_Converter (null); UIHtmlComponent (UI).Finalize; end Finalize; -- ------------------------------ -- Label Component -- ------------------------------ procedure Encode_Begin (UI : in UIOutputLabel; Context : in out Faces_Context'Class) is Writer : Response_Writer_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.Start_Element ("label"); UI.Render_Attributes (Context, LABEL_ATTRIBUTE_NAMES, Writer); declare Value : Util.Beans.Objects.Object := UI.Get_Attribute (Name => "for", Context => Context); begin if not Util.Beans.Objects.Is_Null (Value) then Writer.Write_Attribute ("for", Value); end if; Value := UIOutputLabel'Class (UI).Get_Value; if not Util.Beans.Objects.Is_Null (Value) then declare S : constant String := UIOutputLabel'Class (UI).Get_Formatted_Value (Value, Context); begin if UI.Get_Attribute (Name => "escape", Context => Context, Default => True) then Writer.Write_Text (S); else Writer.Write_Raw (S); end if; end; end if; -- Queue and block any converter exception that could be raised. exception when E : others => Context.Queue_Exception (E); end; end if; end Encode_Begin; procedure Encode_End (UI : in UIOutputLabel; Context : in out Faces_Context'Class) is Writer : Response_Writer_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.End_Element ("label"); end if; end Encode_End; -- ------------------------------ -- OutputFormat Component -- ------------------------------ procedure Encode_Begin (UI : in UIOutputFormat; Context : in out Faces_Context'Class) is use ASF.Components.Core; use ASF.Utils; begin if not UI.Is_Rendered (Context) then return; end if; declare Params : constant UIParameter_Access_Array := Get_Parameters (UI); Values : ASF.Utils.Object_Array (Params'Range); Result : Ada.Strings.Unbounded.Unbounded_String; Fmt : constant String := EL.Objects.To_String (UI.Get_Value); begin -- Get the values associated with the parameters. for I in Params'Range loop Values (I) := Params (I).Get_Value (Context); end loop; Formats.Format (Fmt, Values, Result); UI.Write_Output (Context => Context, Value => To_String (Result)); end; end Encode_Begin; begin Utils.Set_Text_Attributes (TEXT_ATTRIBUTE_NAMES); Utils.Set_Text_Attributes (LABEL_ATTRIBUTE_NAMES); Utils.Set_Interactive_Attributes (LABEL_ATTRIBUTE_NAMES); end ASF.Components.Html.Text;
Implement Get_Converter function (moved from AWA.Components.Base package
Implement Get_Converter function (moved from AWA.Components.Base package
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6d6673c50fa72efb938c4b97bac64f626b711b84
orka/src/orka/interface/orka-windows.ads
orka/src/orka/interface/orka-windows.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. limited with Orka.Contexts; with Orka.Inputs.Pointers; package Orka.Windows is pragma Preelaborate; type Window is limited interface; type Window_Ptr is not null access all Window'Class; function Create_Window (Context : Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return Window is abstract; function Pointer_Input (Object : Window) return Inputs.Pointers.Pointer_Input_Ptr is abstract; function Width (Object : Window) return Positive is abstract; function Height (Object : Window) return Positive is abstract; procedure Set_Title (Object : in out Window; Value : String) is abstract; -- Set the title of the window -- -- Task safety: Must only be called from the environment task. procedure Close (Object : in out Window) is abstract; function Should_Close (Object : Window) return Boolean is abstract; procedure Process_Input (Object : in out Window) is abstract; -- Process window and input events -- -- Task safety: Must only be called from the environment task. procedure Swap_Buffers (Object : in out Window) is abstract; -- Swap the front and back buffers of the window -- -- Task safety: Must only be called from the rendering task. procedure Set_Vertical_Sync (Object : in out Window; Enable : Boolean) is abstract; -- Request the vertical retrace synchronization or vsync to be enabled -- or disabled -- -- Vsync causes the video driver to wait for a screen update before -- swapping the buffers. The video driver may ignore the request. -- Enablng vsync avoids tearing. end Orka.Windows;
-- 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. limited with Orka.Contexts; with Orka.Inputs.Pointers; package Orka.Windows is pragma Preelaborate; type Window is limited interface; function Create_Window (Context : Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return Window is abstract; function Pointer_Input (Object : Window) return Inputs.Pointers.Pointer_Input_Ptr is abstract; function Width (Object : Window) return Positive is abstract; function Height (Object : Window) return Positive is abstract; procedure Set_Title (Object : in out Window; Value : String) is abstract; -- Set the title of the window -- -- Task safety: Must only be called from the environment task. procedure Close (Object : in out Window) is abstract; function Should_Close (Object : Window) return Boolean is abstract; procedure Swap_Buffers (Object : in out Window) is abstract; -- Swap the front and back buffers of the window -- -- Task safety: Must only be called from the rendering task. procedure Set_Vertical_Sync (Object : in out Window; Enable : Boolean) is abstract; -- Request the vertical retrace synchronization or vsync to be enabled -- or disabled -- -- Vsync causes the video driver to wait for a screen update before -- swapping the buffers. The video driver may ignore the request. -- Enablng vsync avoids tearing. end Orka.Windows;
Remove type Window_Ptr and procedure Process_Input in Orka.Windows
orka: Remove type Window_Ptr and procedure Process_Input in Orka.Windows Type Window_Ptr is no longer needed after removing the parameter Window from the generic package Orka.Loops. Procedure Process_Input is removed since AWT.Process_Events will process input (and other) events for the focused window, not necessarily the used Window object. Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
2578afda1432645b4e2abc450237dc2e35d1b3b1
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- Wiki rendering example -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Characters.Conversions; with GNAT.Command_Line; with Util.Files; with Wiki.Utils; procedure Render is use GNAT.Command_Line; use Ada.Strings.Unbounded; use Ada.Characters.Conversions; procedure Usage; procedure Usage is begin Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text"); Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-d] [-c] {wiki-file}"); Ada.Text_IO.Put_Line (" -t Render to text only"); Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content"); Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content"); Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content"); Ada.Text_IO.Put_Line (" -g Render a Google wiki content"); Ada.Text_IO.Put_Line (" -c Render a Creole wiki content"); end Usage; Count : Natural := 0; Html_Mode : Boolean := True; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; begin loop case Getopt ("m M d c g t") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; when 'g' => Syntax := Wiki.SYNTAX_GOOGLE; when 't' => Html_Mode := False; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; Util.Files.Read_File (Name, Data); if Html_Mode then Ada.Text_IO.Put_Line (Wiki.Utils.To_Html (To_Wide_Wide_String (To_String (Data)), Syntax)); else Ada.Text_IO.Put_Line (Wiki.Utils.To_Text (To_Wide_Wide_String (To_String (Data)), Syntax)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Render;
----------------------------------------------------------------------- -- render -- Wiki rendering example -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with GNAT.Command_Line; with Wiki.Documents; with Wiki.Parsers; with Wiki.Filters.TOC; with Wiki.Filters.Html; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; procedure Render is use GNAT.Command_Line; use Ada.Strings.Unbounded; procedure Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String); procedure Render_Text (Doc : in out Wiki.Documents.Document); procedure Usage is begin Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text"); Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-d] [-c] [-s style] {wiki-file}"); Ada.Text_IO.Put_Line (" -t Render to text only"); Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content"); Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content"); Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content"); Ada.Text_IO.Put_Line (" -g Render a Google wiki content"); Ada.Text_IO.Put_Line (" -c Render a Creole wiki content"); Ada.Text_IO.Put_Line (" -s style Use the CSS style file"); end Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String) is Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin if Length (Style) > 0 then Output.Start_Element ("html"); Output.Start_Element ("head"); Output.Start_Element ("link"); Output.Write_Attribute ("type", "text/css"); Output.Write_Attribute ("rel", "stylesheet"); Output.Write_Attribute ("href", To_String (Style)); Output.End_Element ("link"); Output.End_Element ("head"); Output.Start_Element ("body"); end if; Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (True); Renderer.Render (Doc); if Length (Style) > 0 then Output.End_Element ("body"); Output.End_Element ("html"); end if; end Render_Html; procedure Render_Text (Doc : in out Wiki.Documents.Document) is Output : aliased Wiki.Streams.Text_IO.File_Output_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); end Render_Text; Count : Natural := 0; Html_Mode : Boolean := True; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; Style : Unbounded_String; begin loop case Getopt ("m M d c g t s:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; when 'g' => Syntax := Wiki.SYNTAX_GOOGLE; when 't' => Html_Mode := False; when 's' => Style := To_Unbounded_String (Parameter); when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; -- Open the file and parse it (assume UTF-8). Input.Open (Name, "WCEM=8"); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Input'Unchecked_Access, Doc); -- Render the document in text or HTML. if Html_Mode then Render_Html (Doc, Style); else Render_Text (Doc); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Render;
Use the Text_IO streams to read and write the result Add a -s <style> option to emit a HTML head with CSS style
Use the Text_IO streams to read and write the result Add a -s <style> option to emit a HTML head with CSS style
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
508bc763a5a10adec1ff87615e50cf1658684f2f
regtests/el-beans-tests.adb
regtests/el-beans-tests.adb
----------------------------------------------------------------------- -- EL.Beans.Tests - Testsuite for EL.Beans -- 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 Test_Bean; with Util.Beans.Objects; with EL.Contexts.Default; package body EL.Beans.Tests is use Util.Tests; use Util.Beans.Objects; use Test_Bean; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test EL.Beans.Add_Parameter", Test_Add_Parameter'Access); Caller.Add_Test (Suite, "Test EL.Beans.Initialize", Test_Initialize'Access); end Add_Tests; -- ------------------------------ -- Test Add_Parameter -- ------------------------------ procedure Test_Add_Parameter (T : in out Test) is P : Param_Vectors.Vector; Context : EL.Contexts.Default.Default_Context; begin -- Add a constant parameter. Add_Parameter (Container => P, Name => "firstName", Value => "my name", Context => Context); Assert_Equals (T, 1, Integer (P.Length), "Parameter was not added"); T.Assert_Equals ("firstName", P.Element (1).Name, "Invalid parameter name"); T.Assert (P.Element (1).Value.Is_Constant, "Value should be a constant"); T.Assert_Equals ("my name", Util.Beans.Objects.To_String (P.Element (1).Value.Get_Value (Context)), "Invalid value"); -- Add an expression parameter. Add_Parameter (Container => P, Name => "lastName", Value => "#{name}", Context => Context); Assert_Equals (T, 2, Integer (P.Length), "Parameter was not added"); end Test_Add_Parameter; -- ------------------------------ -- Test the Initialize procedure with a set of expressions -- ------------------------------ procedure Test_Initialize (T : in out Test) is P : Param_Vectors.Vector; Context : EL.Contexts.Default.Default_Context; User : Person_Access := Create_Person ("Joe", "Black", 42); Bean : Person_Access := Create_Person ("", "", 0); begin Context.Set_Variable ("user", User); Add_Parameter (P, "firstName", "#{user.firstName}", Context); Add_Parameter (P, "lastName", "#{user.lastName}", Context); Add_Parameter (P, "age", "#{user.age + 2}", Context); Initialize (Bean.all, P, Context); T.Assert_Equals ("Joe", Bean.First_Name, "First name not initialized"); T.Assert_Equals ("Black", Bean.Last_Name, "Last name not initialized"); Assert_Equals (T, 44, Integer (Bean.Age), "Age was not initialized"); Free (Bean); Free (User); end Test_Initialize; end EL.Beans.Tests;
----------------------------------------------------------------------- -- EL.Beans.Tests - Testsuite for EL.Beans -- 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 Test_Bean; with Util.Beans.Objects; with EL.Contexts.Default; package body EL.Beans.Tests is use Util.Tests; use Util.Beans.Objects; use Test_Bean; package Caller is new Util.Test_Caller (Test, "EL.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test EL.Beans.Add_Parameter", Test_Add_Parameter'Access); Caller.Add_Test (Suite, "Test EL.Beans.Initialize", Test_Initialize'Access); end Add_Tests; -- ------------------------------ -- Test Add_Parameter -- ------------------------------ procedure Test_Add_Parameter (T : in out Test) is P : Param_Vectors.Vector; Context : EL.Contexts.Default.Default_Context; begin -- Add a constant parameter. Add_Parameter (Container => P, Name => "firstName", Value => "my name", Context => Context); Assert_Equals (T, 1, Integer (P.Length), "Parameter was not added"); T.Assert_Equals ("firstName", P.Element (1).Name, "Invalid parameter name"); T.Assert (P.Element (1).Value.Is_Constant, "Value should be a constant"); T.Assert_Equals ("my name", Util.Beans.Objects.To_String (P.Element (1).Value.Get_Value (Context)), "Invalid value"); -- Add an expression parameter. Add_Parameter (Container => P, Name => "lastName", Value => "#{name}", Context => Context); Assert_Equals (T, 2, Integer (P.Length), "Parameter was not added"); end Test_Add_Parameter; -- ------------------------------ -- Test the Initialize procedure with a set of expressions -- ------------------------------ procedure Test_Initialize (T : in out Test) is P : Param_Vectors.Vector; Context : EL.Contexts.Default.Default_Context; User : Person_Access := Create_Person ("Joe", "Black", 42); Bean : Person_Access := Create_Person ("", "", 0); begin Context.Set_Variable ("user", User); Add_Parameter (P, "firstName", "#{user.firstName}", Context); Add_Parameter (P, "lastName", "#{user.lastName}", Context); Add_Parameter (P, "age", "#{user.age + 2}", Context); Initialize (Bean.all, P, Context); T.Assert_Equals ("Joe", Bean.First_Name, "First name not initialized"); T.Assert_Equals ("Black", Bean.Last_Name, "Last name not initialized"); Assert_Equals (T, 44, Integer (Bean.Age), "Age was not initialized"); Free (Bean); Free (User); end Test_Initialize; end EL.Beans.Tests;
Use the test name EL.Beans
Use the test name EL.Beans
Ada
apache-2.0
stcarrez/ada-el
5509229737f749ab687f61ccdbcc98453473b168
samples/beans/messages.adb
samples/beans/messages.adb
----------------------------------------------------------------------- -- messages - A simple memory-based forum -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Events.Faces.Actions; package body Messages is use Ada.Strings.Unbounded; Database : aliased Forum; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ function Get_Value (From : in Message_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "text" then return Util.Beans.Objects.To_Object (From.Text); elsif Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "id" then return Util.Beans.Objects.To_Object (Integer (From.Id)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ procedure Set_Value (From : in out Message_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "text" then From.Text := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "id" then From.Id := Message_Id (Util.Beans.Objects.To_Integer (Value)); end if; end Set_Value; -- ------------------------------ -- Post the message. -- ------------------------------ procedure Post (From : in out Message_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin if Length (From.Text) > 200 then Ada.Strings.Unbounded.Replace_Slice (From.Text, 200, Length (From.Text), "..."); end if; Database.Post (From); Outcome := To_Unbounded_String ("posted"); end Post; package Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Message_Bean, Method => Post, Name => "post"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Post_Binding.Proxy'Unchecked_Access, Post_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Message_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a message bean instance. -- ------------------------------ function Create_Message_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Message_Bean_Access := new Message_Bean; begin return Result.all'Access; end Create_Message_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Forum_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (Integer (From.Get_Count)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : in Forum_Bean) return Natural is pragma Unreferenced (From); begin return Database.Get_Message_Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out Forum_Bean; Index : in Natural) is begin From.Pos := Message_Id (Index); From.Msg := Database.Get_Message (From.Pos); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : in Forum_Bean) return Util.Beans.Objects.Object is begin return From.Current; end Get_Row; -- ------------------------------ -- Create the list of messages. -- ------------------------------ function Create_Message_List return Util.Beans.Basic.Readonly_Bean_Access is F : constant Forum_Bean_Access := new Forum_Bean; begin F.Current := Util.Beans.Objects.To_Object (F.Msg'Access, Util.Beans.Objects.STATIC); return F.all'Access; end Create_Message_List; protected body Forum is -- ------------------------------ -- Post the message in the forum. -- ------------------------------ procedure Post (Message : in Message_Bean) is use type Ada.Containers.Count_Type; begin if Messages.Length > 100 then Messages.Delete (Message_Id'First); end if; Messages.Append (Message); end Post; -- ------------------------------ -- Delete the message identified by <b>Id</b>. -- ------------------------------ procedure Delete (Id : in Message_Id) is begin Messages.Delete (Id); end Delete; -- ------------------------------ -- Get the message identified by <b>Id</b>. -- ------------------------------ function Get_Message (Id : in Message_Id) return Message_Bean is begin return Messages.Element (Id); end Get_Message; -- ------------------------------ -- Get the number of messages in the forum. -- ------------------------------ function Get_Message_Count return Natural is begin return Natural (Messages.Length); end Get_Message_Count; end Forum; end Messages;
----------------------------------------------------------------------- -- messages - A simple memory-based forum -- 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.Calendar; with Util.Beans.Objects.Time; with ASF.Events.Faces.Actions; package body Messages is use Ada.Strings.Unbounded; Database : aliased Forum; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ function Get_Value (From : in Message_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "text" then return Util.Beans.Objects.To_Object (From.Text); elsif Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "id" then return Util.Beans.Objects.To_Object (Integer (From.Id)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ procedure Set_Value (From : in out Message_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "text" then From.Text := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "id" then From.Id := Message_Id (Util.Beans.Objects.To_Integer (Value)); end if; end Set_Value; -- ------------------------------ -- Post the message. -- ------------------------------ procedure Post (From : in out Message_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin if Length (From.Text) > 200 then Ada.Strings.Unbounded.Replace_Slice (From.Text, 200, Length (From.Text), "..."); end if; Database.Post (From); Outcome := To_Unbounded_String ("posted"); end Post; package Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Message_Bean, Method => Post, Name => "post"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Post_Binding.Proxy'Unchecked_Access, Post_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Message_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a message bean instance. -- ------------------------------ function Create_Message_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Message_Bean_Access := new Message_Bean; begin return Result.all'Access; end Create_Message_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Forum_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (Integer (From.Get_Count)); elsif Name = "today" then return Util.Beans.Objects.Time.To_Object (Ada.Calendar.Clock); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : in Forum_Bean) return Natural is pragma Unreferenced (From); begin return Database.Get_Message_Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out Forum_Bean; Index : in Natural) is begin From.Pos := Message_Id (Index); From.Msg := Database.Get_Message (From.Pos); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : in Forum_Bean) return Util.Beans.Objects.Object is begin return From.Current; end Get_Row; -- ------------------------------ -- Create the list of messages. -- ------------------------------ function Create_Message_List return Util.Beans.Basic.Readonly_Bean_Access is F : constant Forum_Bean_Access := new Forum_Bean; begin F.Current := Util.Beans.Objects.To_Object (F.Msg'Access, Util.Beans.Objects.STATIC); return F.all'Access; end Create_Message_List; protected body Forum is -- ------------------------------ -- Post the message in the forum. -- ------------------------------ procedure Post (Message : in Message_Bean) is use type Ada.Containers.Count_Type; begin if Messages.Length > 100 then Messages.Delete (Message_Id'First); end if; Messages.Append (Message); end Post; -- ------------------------------ -- Delete the message identified by <b>Id</b>. -- ------------------------------ procedure Delete (Id : in Message_Id) is begin Messages.Delete (Id); end Delete; -- ------------------------------ -- Get the message identified by <b>Id</b>. -- ------------------------------ function Get_Message (Id : in Message_Id) return Message_Bean is begin return Messages.Element (Id); end Get_Message; -- ------------------------------ -- Get the number of messages in the forum. -- ------------------------------ function Get_Message_Count return Natural is begin return Natural (Messages.Length); end Get_Message_Count; end Forum; end Messages;
Add a bean value 'today' to retrieve the current date and time in an XHTML view
Add a bean value 'today' to retrieve the current date and time in an XHTML view
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
9a14ca43dfcd30df427d1e5934229da082d8c632
regtests/util-events-timers-tests.ads
regtests/util-events-timers-tests.ads
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Events.Timers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test and Util.Events.Timers.Timer with record Count : Natural := 0; Repeat : Natural := 0; end record; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class); -- Test empty timers. procedure Test_Empty_Timer (T : in out Test); procedure Test_Timer_Event (T : in out Test); -- Test repeating timers. procedure Test_Repeat_Timer (T : in out Test); end Util.Events.Timers.Tests;
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Events.Timers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test and Util.Events.Timers.Timer with record Count : Natural := 0; Repeat : Natural := 0; end record; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class); -- Test empty timers. procedure Test_Empty_Timer (T : in out Test); procedure Test_Timer_Event (T : in out Test); -- Test repeating timers. procedure Test_Repeat_Timer (T : in out Test); -- Test executing several timers. procedure Test_Many_Timers (T : in out Test); end Util.Events.Timers.Tests;
Declare the Test_Many_Timers procedure
Declare the Test_Many_Timers procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
50306e187e10d25b15eb85ad611b6fceccae30c4
awa/plugins/awa-comments/src/awa-comments-modules.ads
awa/plugins/awa-comments/src/awa-comments-modules.ads
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Modules.Get; with AWA.Comments.Models; package AWA.Comments.Modules is NAME : constant String := "comments"; type Comment_Module is new AWA.Modules.Module with null record; type Comment_Module_Access is access all Comment_Module'Class; overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Load the comment identified by the given identifier. procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier); -- Create a new comment for the associated database entity. procedure Create_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class); function Get_Comment_Module is new AWA.Modules.Get (Comment_Module, Comment_Module_Access, NAME); end AWA.Comments.Modules;
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Modules.Get; with AWA.Comments.Models; package AWA.Comments.Modules is NAME : constant String := "comments"; type Comment_Module is new AWA.Modules.Module with null record; type Comment_Module_Access is access all Comment_Module'Class; overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Load the comment identified by the given identifier. procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier); -- Create a new comment for the associated database entity. procedure Create_Comment (Model : in Comment_Module; Permission : in String; Entity_Type : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class); function Get_Comment_Module is new AWA.Modules.Get (Comment_Module, Comment_Module_Access, NAME); end AWA.Comments.Modules;
Change the Create_Comment to specify the entity type
Change the Create_Comment to specify the entity type
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
0f9b58fd2c671f011a1f80ca93d84b257501887b
src/security-policies.ads
src/security-policies.ads
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Policy is new Ada.Finalization.Limited_Controlled with null record; type Policy_Access is access all Policy'Class; procedure Set_Reader_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Get the policy name. function Get_Name (From : in Policy) return String; Invalid_Name : exception; type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access; pragma Inline_Always (Get_Controller); -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private use Util.Strings; subtype Permission_Index is Permissions.Permission_Index; type Permission_Type_Array is array (1 .. 10) of Permission_Type; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Manager is new Ada.Finalization.Limited_Controlled with record -- Cache : Rules_Ref_Access; -- Policies : Policy_Vector.Vector; Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; end record; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Policy is new Ada.Finalization.Limited_Controlled with null record; type Policy_Access is access all Policy'Class; procedure Set_Reader_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Get the policy name. function Get_Name (From : in Policy) return String; Invalid_Name : exception; type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access; pragma Inline_Always (Get_Controller); -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private use Util.Strings; subtype Permission_Index is Permissions.Permission_Index; type Permission_Type_Array is array (1 .. 10) of Permission_Type; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Manager is new Ada.Finalization.Limited_Controlled with record -- Cache : Rules_Ref_Access; -- Policies : Policy_Vector.Vector; Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; end record; end Security.Policies;
Document Add_Permission
Document Add_Permission
Ada
apache-2.0
stcarrez/ada-security
2ba93b7b05d1b441cee11d5a94a8c0bc8d9896e9
src/security-policies.ads
src/security-policies.ads
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; -- == Security Policies == -- The Security Policy defines and implements the set of security rules that specify -- how to protect the system or resources. The <tt>Policy_Manager</tt> maintains -- the security policies. These policies are registered when an application starts, -- before reading the policy configuration files. -- -- [[images/PolicyModel.png]] -- -- While the policy configuration files are processed, the policy instances that have been -- registered will create a security controller and bind it to a given permission. After -- successful initialization, the <tt>Policy_Manager</tt> contains a list of securiy -- controllers which are associated with each permission defined by the application. -- -- === Authenticated Permission === -- The `auth-permission` is a pre-defined permission that can be configured in the XML -- configuration. Basically the permission is granted if the security context has a principal. -- Otherwise the permission is denied. The permission is assigned a name and is declared -- as follows: -- -- <policy-rules> -- <auth-permission> -- <name>view-profile</name> -- </auth-permission> -- </policy-rules> -- -- This example defines the `view-profile` permission. -- -- === Grant Permission === -- The `grant-permission` is another pre-defined permission that gives the permission whatever -- the security context. The permission is defined as follows: -- -- <policy-rules> -- <grant-permission> -- <name>anonymous</name> -- </grant-permission> -- </policy-rules> -- -- This example defines the `anonymous` permission. -- -- @include security-policies-roles.ads -- @include security-policies-urls.ads --- @include security-controllers.ads package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Returns True if the security controller is defined for the given permission index. function Has_Controller (Manager : in Policy_Manager; Index : in Permissions.Permission_Index) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser); -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index := Policy_Index'First; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; with Util.Serialize.Mappers; limited with Security.Controllers; limited with Security.Contexts; -- == Security Policies == -- The Security Policy defines and implements the set of security rules that specify -- how to protect the system or resources. The <tt>Policy_Manager</tt> maintains -- the security policies. These policies are registered when an application starts, -- before reading the policy configuration files. -- -- [[images/PolicyModel.png]] -- -- While the policy configuration files are processed, the policy instances that have been -- registered will create a security controller and bind it to a given permission. After -- successful initialization, the <tt>Policy_Manager</tt> contains a list of securiy -- controllers which are associated with each permission defined by the application. -- -- === Authenticated Permission === -- The `auth-permission` is a pre-defined permission that can be configured in the XML -- configuration. Basically the permission is granted if the security context has a principal. -- Otherwise the permission is denied. The permission is assigned a name and is declared -- as follows: -- -- <policy-rules> -- <auth-permission> -- <name>view-profile</name> -- </auth-permission> -- </policy-rules> -- -- This example defines the `view-profile` permission. -- -- === Grant Permission === -- The `grant-permission` is another pre-defined permission that gives the permission whatever -- the security context. The permission is defined as follows: -- -- <policy-rules> -- <grant-permission> -- <name>anonymous</name> -- </grant-permission> -- </policy-rules> -- -- This example defines the `anonymous` permission. -- -- @include security-policies-roles.ads -- @include security-policies-urls.ads --- @include security-controllers.ads package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Mapper : in out Util.Serialize.Mappers.Processing) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Returns True if the security controller is defined for the given permission index. function Has_Controller (Manager : in Policy_Manager; Index : in Permissions.Permission_Index) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Manager : in out Policy_Manager; Mapper : in out Util.Serialize.Mappers.Processing); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser); -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index := Policy_Index'First; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
Change the Mapper parameter to use the Mappers.Processing type
Change the Mapper parameter to use the Mappers.Processing type
Ada
apache-2.0
stcarrez/ada-security
182421c043c15a88a94a88185840e7fb34663575
src/gen-artifacts-query.adb
src/gen-artifacts-query.adb
----------------------------------------------------------------------- -- gen-artifacts-query -- Query artifact for Code Generator -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Gen.Configs; with Gen.Utils; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Util.Log.Loggers; with Util.Encoders.HMAC.SHA1; -- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of -- data structures returned by queries. package body Gen.Artifacts.Query is use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Model.Queries; use Gen.Configs; use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query"); -- ------------------------------ -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. -- ------------------------------ procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node); procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node); procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition; Node : in DOM.Core.Node); Hash : Unbounded_String; -- ------------------------------ -- Register the column definition in the table -- ------------------------------ procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Column, "name"); C : constant Column_Definition_Access := new Column_Definition; begin C.Initialize (Name, Column); C.Number := Table.Members.Get_Count; Table.Members.Append (C); C.Type_Name := To_Unbounded_String (Gen.Utils.Get_Normalized_Type (Column, "type")); C.Is_Inserted := False; C.Is_Updated := False; C.Not_Null := False; C.Unique := False; -- Construct the hash for this column mapping. Append (Hash, ",type="); Append (Hash, C.Type_Name); Append (Hash, ",name="); Append (Hash, Name); end Register_Column; -- ------------------------------ -- Register all the columns defined in the table -- ------------------------------ procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Column); begin Log.Debug ("Register columns from query {0}", Table.Name); Iterate (Table, Node, "property"); end Register_Columns; -- ------------------------------ -- Register a new class definition in the model. -- ------------------------------ procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); begin Query.Initialize (Name, Node); Query.Set_Table_Name (To_String (Name)); if Name /= "" then Query.Name := Name; else Query.Name := To_Unbounded_String (Gen.Utils.Get_Query_Name (Path)); end if; -- Construct the hash for this column mapping. Append (Hash, "class="); Append (Hash, Query.Name); Log.Debug ("Register query {0} with type {1}", Query.Name, Query.Type_Name); Register_Columns (Query, Node); end Register_Mapping; -- ------------------------------ -- Register a new query. -- ------------------------------ procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); C : Column_Definition_Access; begin Query.Add_Query (Name, C); end Register_Query; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node) is procedure Iterate_Mapping is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition, Process => Register_Mapping); procedure Iterate_Query is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition, Process => Register_Query); Table : constant Query_Definition_Access := new Query_Definition; Pkg : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "package"); Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "table"); begin Table.Initialize (Name, Node); Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path)); Table.Pkg_Name := Pkg; Iterate_Mapping (Query_Definition (Table.all), Node, "class"); Iterate_Query (Query_Definition (Table.all), Node, "query"); if Length (Table.Pkg_Name) = 0 then Context.Error ("Missing or empty package attribute"); else Model.Register_Query (Table); end if; Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash)); Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries", Data => To_String (Hash)); end Register_Mapping; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition, Process => Register_Mapping); begin Log.Debug ("Initializing query artifact for the configuration"); Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context); Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is pragma Unreferenced (Handler); begin Log.Debug ("Preparing the model for query"); if Model.Has_Packages then Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); end if; end Prepare; end Gen.Artifacts.Query;
----------------------------------------------------------------------- -- gen-artifacts-query -- Query artifact for Code Generator -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Gen.Configs; with Gen.Utils; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Util.Log.Loggers; with Util.Encoders.HMAC.SHA1; -- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of -- data structures returned by queries. package body Gen.Artifacts.Query is use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Model.Queries; use Gen.Configs; use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query"); -- ------------------------------ -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. -- ------------------------------ procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node); procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node); procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition; Node : in DOM.Core.Node); Hash : Unbounded_String; -- ------------------------------ -- Register the column definition in the table -- ------------------------------ procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Column, "name"); C : Column_Definition_Access; begin Table.Add_Column (Name, C); C.Initialize (Name, Column); C.Type_Name := To_Unbounded_String (Gen.Utils.Get_Normalized_Type (Column, "type")); C.Is_Inserted := False; C.Is_Updated := False; C.Not_Null := False; C.Unique := False; -- Construct the hash for this column mapping. Append (Hash, ",type="); Append (Hash, C.Type_Name); Append (Hash, ",name="); Append (Hash, Name); end Register_Column; -- ------------------------------ -- Register all the columns defined in the table -- ------------------------------ procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Column); begin Log.Debug ("Register columns from query {0}", Table.Name); Iterate (Table, Node, "property"); end Register_Columns; -- ------------------------------ -- Register a new class definition in the model. -- ------------------------------ procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); begin Query.Initialize (Name, Node); Query.Set_Table_Name (To_String (Name)); if Name /= "" then Query.Name := Name; else Query.Name := To_Unbounded_String (Gen.Utils.Get_Query_Name (Path)); end if; -- Construct the hash for this column mapping. Append (Hash, "class="); Append (Hash, Query.Name); Log.Debug ("Register query {0} with type {1}", Query.Name, Query.Type_Name); Register_Columns (Query, Node); end Register_Mapping; -- ------------------------------ -- Register a new query. -- ------------------------------ procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); C : Column_Definition_Access; begin Query.Add_Query (Name, C); end Register_Query; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node) is procedure Iterate_Mapping is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition, Process => Register_Mapping); procedure Iterate_Query is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition, Process => Register_Query); Table : constant Query_Definition_Access := new Query_Definition; Pkg : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "package"); Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "table"); begin Table.Initialize (Name, Node); Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path)); Table.Pkg_Name := Pkg; Iterate_Mapping (Query_Definition (Table.all), Node, "class"); Iterate_Query (Query_Definition (Table.all), Node, "query"); if Length (Table.Pkg_Name) = 0 then Context.Error ("Missing or empty package attribute"); else Model.Register_Query (Table); end if; Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash)); Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries", Data => To_String (Hash)); end Register_Mapping; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition, Process => Register_Mapping); begin Log.Debug ("Initializing query artifact for the configuration"); Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context); Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is pragma Unreferenced (Handler); begin Log.Debug ("Preparing the model for query"); if Model.Has_Packages then Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); end if; end Prepare; end Gen.Artifacts.Query;
Use Add_Column to create a new column in a table
Use Add_Column to create a new column in a table
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
04af2bc88f77ecb192b83a6bedd10114efae52bb
src/gen-model-tables.ads
src/gen-model-tables.ads
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
Add support to manage table dependencies - keep the dependencies for each table, - new operation Depends_On to get the dependency status bewteen two tables
Add support to manage table dependencies - keep the dependencies for each table, - new operation Depends_On to get the dependency status bewteen two tables
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
4015b4813ffa288750a1cf7b7827bb7aa3858cad
src/parameters.ads
src/parameters.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Definitions; use Definitions; with HelperText; private with Utilities; package Parameters is package HT renames HelperText; no_ccache : constant String := "none"; no_unkindness : constant String := "none"; raven_confdir : constant String := host_localbase & "/etc/ravenadm"; type configuration_record is record profile : HT.Text; dir_sysroot : HT.Text; dir_toolchain : HT.Text; dir_localbase : HT.Text; dir_conspiracy : HT.Text; dir_unkindness : HT.Text; dir_distfiles : HT.Text; dir_packages : HT.Text; dir_ccache : HT.Text; dir_buildbase : HT.Text; dir_logs : HT.Text; num_builders : builders; jobs_limit : builders; avoid_tmpfs : Boolean; record_options : Boolean; avec_ncurses : Boolean; defer_prebuilt : Boolean; -- Computed, not saved number_cores : cpu_range; dir_repository : HT.Text; sysroot_pkg8 : HT.Text; end record; configuration : configuration_record; active_profile : HT.Text; -- This procedure will create a default configuration file if one -- does not already exist, otherwise it will it load it. In every case, -- the "configuration" record will be populated after this is run. -- returns "True" on success function load_configuration return Boolean; -- Maybe a previously valid directory path has been removed. This -- function returns true when all the paths still work. -- The configuration must be loaded before it's run, of course. function all_paths_valid return Boolean; -- Return true if the localbase is set to someplace it really shouldn't be function forbidden_localbase (candidate : String) return Boolean; -- Return a profile record filled with dynamic defaults. function default_profile (new_profile : String) return configuration_record; -- Delete any existing profile data and create a new profile. -- Typically a save operation follows. procedure insert_profile (confrec : configuration_record); -- Create or overwrite a complete ravenadm.ini file using internal data at IFM procedure rewrite_configuration; -- Return True if 3 or more sections exist (1 is global, the rest must be profiles) function alternative_profiles_exist return Boolean; -- Return a LF-delimited list of profiles contained in ravenadm.ini function list_profiles return String; -- Remove an entire profile from the configuration and save it. procedure delete_profile (profile : String); -- Updates master section with new profile name and initiates a transfer procedure switch_profile (to_profile : String); private package UTL renames Utilities; memory_probe : exception; profile_DNE : exception; memory_megs : Natural := 0; -- Default Sizing by number of CPUS -- 1 CPU :: 1 Builder, 1 job per builder -- 2/3 CPU :: 2 builders, 2 jobs per builder -- 4/5 CPU :: 3 builders, 3 jobs per builder -- 6/7 CPU :: 4 builders, 3 jobs per builder -- 8/9 CPU :: 6 builders, 4 jobs per builder -- 10/11 CPU :: 8 builders, 4 jobs per builder -- 12+ CPU :: floor (75% * CPU), 5 jobs per builder Field_01 : constant String := "directory_sysroot"; Field_16 : constant String := "directory_toolchain"; Field_02 : constant String := "directory_localbase"; Field_03 : constant String := "directory_conspiracy"; Field_04 : constant String := "directory_unkindness"; Field_05 : constant String := "directory_distfiles"; Field_06 : constant String := "directory_packages"; Field_07 : constant String := "directory_ccache"; Field_08 : constant String := "directory_buildbase"; Field_09 : constant String := "directory_logs"; Field_10 : constant String := "number_of_builders"; Field_11 : constant String := "max_jobs_per_builder"; Field_12 : constant String := "avoid_tmpfs"; Field_13 : constant String := "record_default_options"; Field_14 : constant String := "display_with_ncurses"; Field_15 : constant String := "leverage_prebuilt"; global_01 : constant String := "profile_selected"; global_02 : constant String := "url_conspiracy"; first_profile : constant String := "primary"; raven_var : constant String := "/var/ravenports"; master_section : constant String := "Global Configuration"; pri_packages : constant String := raven_var & "/[X]_packages"; pri_logs : constant String := raven_var & "/logs/[X]"; pri_buildbase : constant String := "/usr/obj/ravenports"; ravenadm_ini : constant String := "ravenadm.ini"; conf_location : constant String := raven_confdir & "/" & ravenadm_ini; std_localbase : constant String := "/raven"; std_distfiles : constant String := raven_var & "/distfiles"; std_conspiracy : constant String := raven_var & "/conspiracy"; std_sysroot : constant String := std_localbase & "/share/raven-sysroot/" & UTL.mixed_opsys (platform_type); std_toolchain : constant String := std_localbase & "/toolchain"; procedure query_physical_memory; procedure query_physical_memory_linux; procedure query_physical_memory_sunos; function enough_memory (num_builders : builders) return Boolean; procedure default_parallelism (num_cores : cpu_range; num_builders : out Integer; jobs_per_builder : out Integer); -- Copy from IFM to configuration record, updating type as necessary. -- If values are missing, use default values. -- If profile in global does not exist, throw exception procedure transfer_configuration; -- Determine and store number of cores. It's needed for dynamic configuration and -- the value is used in the build cycle as well. procedure set_cores; -- Platform-specific routines to determine ncpu function get_number_cpus return Positive; -- Updates the global section to indicate active profile procedure change_active_profile (new_active_profile : String); end Parameters;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Definitions; use Definitions; with HelperText; private with Utilities; package Parameters is package HT renames HelperText; no_ccache : constant String := "none"; no_unkindness : constant String := "none"; raven_confdir : constant String := host_localbase & "/etc/ravenadm"; type configuration_record is record profile : HT.Text; dir_sysroot : HT.Text; dir_toolchain : HT.Text; dir_localbase : HT.Text; dir_conspiracy : HT.Text; dir_unkindness : HT.Text; dir_distfiles : HT.Text; dir_packages : HT.Text; dir_ccache : HT.Text; dir_buildbase : HT.Text; dir_logs : HT.Text; num_builders : builders; jobs_limit : builders; avoid_tmpfs : Boolean; record_options : Boolean; avec_ncurses : Boolean; defer_prebuilt : Boolean; -- Computed, not saved number_cores : cpu_range; dir_repository : HT.Text; sysroot_pkg8 : HT.Text; end record; configuration : configuration_record; active_profile : HT.Text; -- This procedure will create a default configuration file if one -- does not already exist, otherwise it will it load it. In every case, -- the "configuration" record will be populated after this is run. -- returns "True" on success function load_configuration return Boolean; -- Maybe a previously valid directory path has been removed. This -- function returns true when all the paths still work. -- The configuration must be loaded before it's run, of course. function all_paths_valid return Boolean; -- Return true if the localbase is set to someplace it really shouldn't be function forbidden_localbase (candidate : String) return Boolean; -- Return a profile record filled with dynamic defaults. function default_profile (new_profile : String) return configuration_record; -- Delete any existing profile data and create a new profile. -- Typically a save operation follows. procedure insert_profile (confrec : configuration_record); -- Create or overwrite a complete ravenadm.ini file using internal data at IFM procedure rewrite_configuration; -- Return True if 3 or more sections exist (1 is global, the rest must be profiles) function alternative_profiles_exist return Boolean; -- Return a LF-delimited list of profiles contained in ravenadm.ini function list_profiles return String; -- Remove an entire profile from the configuration and save it. procedure delete_profile (profile : String); -- Updates master section with new profile name and initiates a transfer procedure switch_profile (to_profile : String); private package UTL renames Utilities; memory_probe : exception; profile_DNE : exception; memory_megs : Natural := 0; -- Default Sizing by number of CPUS -- 1 CPU :: 1 Builder, 1 job per builder -- 2/3 CPU :: 2 builders, 2 jobs per builder -- 4/5 CPU :: 3 builders, 3 jobs per builder -- 6/7 CPU :: 4 builders, 3 jobs per builder -- 8/9 CPU :: 6 builders, 4 jobs per builder -- 10/11 CPU :: 8 builders, 4 jobs per builder -- 12+ CPU :: floor (75% * CPU), 5 jobs per builder Field_01 : constant String := "directory_sysroot"; Field_16 : constant String := "directory_toolchain"; Field_02 : constant String := "directory_localbase"; Field_03 : constant String := "directory_conspiracy"; Field_04 : constant String := "directory_unkindness"; Field_05 : constant String := "directory_distfiles"; Field_06 : constant String := "directory_packages"; Field_07 : constant String := "directory_ccache"; Field_08 : constant String := "directory_buildbase"; Field_09 : constant String := "directory_logs"; Field_10 : constant String := "number_of_builders"; Field_11 : constant String := "max_jobs_per_builder"; Field_12 : constant String := "avoid_tmpfs"; Field_13 : constant String := "record_default_options"; Field_14 : constant String := "display_with_ncurses"; Field_15 : constant String := "leverage_prebuilt"; global_01 : constant String := "profile_selected"; global_02 : constant String := "url_conspiracy"; first_profile : constant String := "primary"; raven_var : constant String := "/var/ravenports"; master_section : constant String := "Global Configuration"; pri_packages : constant String := raven_var & "/[X]_packages"; pri_logs : constant String := raven_var & "/logs/[X]"; pri_buildbase : constant String := "/usr/obj/ravenports"; ravenadm_ini : constant String := "ravenadm.ini"; conf_location : constant String := raven_confdir & "/" & ravenadm_ini; std_localbase : constant String := "/raven"; std_distfiles : constant String := raven_var & "/distfiles"; std_conspiracy : constant String := raven_var & "/conspiracy"; std_sysroot : constant String := std_localbase & "/share/raven/sysroot/" & UTL.mixed_opsys (platform_type); std_toolchain : constant String := std_localbase & "/share/raven/toolchain"; procedure query_physical_memory; procedure query_physical_memory_linux; procedure query_physical_memory_sunos; function enough_memory (num_builders : builders) return Boolean; procedure default_parallelism (num_cores : cpu_range; num_builders : out Integer; jobs_per_builder : out Integer); -- Copy from IFM to configuration record, updating type as necessary. -- If values are missing, use default values. -- If profile in global does not exist, throw exception procedure transfer_configuration; -- Determine and store number of cores. It's needed for dynamic configuration and -- the value is used in the build cycle as well. procedure set_cores; -- Platform-specific routines to determine ncpu function get_number_cpus return Positive; -- Updates the global section to indicate active profile procedure change_active_profile (new_active_profile : String); end Parameters;
Adjust 2 defaults (sysroot and toolchain)
Adjust 2 defaults (sysroot and toolchain)
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
b331c1d20debf6e4640c79cd0bb03a37bf6d89cd
regtests/regtests.adb
regtests/regtests.adb
----------------------------------------------------------------------- -- ADO Tests -- Database sequence generator -- Copyright (C) 2009, 2010, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Factory; package body Regtests is Factory : aliased ADO.Sessions.Factory.Session_Factory; Controller : aliased ADO.Sessions.Sources.Data_Source; -- ------------------------------ -- Get the database manager to be used for the unit tests -- ------------------------------ function Get_Controller return ADO.Sessions.Sources.Data_Source'Class is begin return Controller; end Get_Controller; -- ------------------------------ -- Get the readonly connection database to be used for the unit tests -- ------------------------------ function Get_Database return ADO.Sessions.Session is begin return Factory.Get_Session; end Get_Database; -- ------------------------------ -- Get the writeable connection database to be used for the unit tests -- ------------------------------ function Get_Master_Database return ADO.Sessions.Master_Session is begin return Factory.Get_Master_Session; end Get_Master_Database; -- ------------------------------ -- Initialize the test database -- ------------------------------ procedure Initialize (Name : in String) is begin Controller.Set_Connection (Name); Factory.Create (Controller); end Initialize; end Regtests;
----------------------------------------------------------------------- -- regtests -- Support for unit tests -- Copyright (C) 2009, 2010, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Factory; package body Regtests is Factory : aliased ADO.Sessions.Factory.Session_Factory; Controller : aliased ADO.Sessions.Sources.Data_Source; -- ------------------------------ -- Get the database manager to be used for the unit tests -- ------------------------------ function Get_Controller return ADO.Sessions.Sources.Data_Source'Class is begin return Controller; end Get_Controller; -- ------------------------------ -- Get the readonly connection database to be used for the unit tests -- ------------------------------ function Get_Database return ADO.Sessions.Session is begin return Factory.Get_Session; end Get_Database; -- ------------------------------ -- Get the writeable connection database to be used for the unit tests -- ------------------------------ function Get_Master_Database return ADO.Sessions.Master_Session is begin return Factory.Get_Master_Session; end Get_Master_Database; -- ------------------------------ -- Set the audit manager on the factory. -- ------------------------------ procedure Set_Audit_Manager (Manager : in ADO.Audits.Audit_Manager_Access) is begin Factory.Set_Audit_Manager (Manager); end Set_Audit_Manager; -- ------------------------------ -- Initialize the test database -- ------------------------------ procedure Initialize (Name : in String) is begin Controller.Set_Connection (Name); Factory.Create (Controller); end Initialize; end Regtests;
Implement the Set_Audit_Manager procedure
Implement the Set_Audit_Manager procedure
Ada
apache-2.0
stcarrez/ada-ado
ddc50cb35874c0537eae0c9af3dda928e402258d
awa/plugins/awa-wikis/src/awa-wikis-previews.ads
awa/plugins/awa-wikis/src/awa-wikis-previews.ads
----------------------------------------------------------------------- -- awa-wikis-previews -- Wiki preview management -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with AWA.Modules; with AWA.Jobs.Services; with AWA.Jobs.Modules; with AWA.Wikis.Modules; with AWA.Wikis.Models; -- == Wiki Preview Module == -- The <tt>AWA.Wikis.Previews</tt> package implements a preview image generation for a wiki page. -- This module is optional, it is possible to use the wikis without preview support. When the -- module is registered, it listens to wiki page lifecycle events. When a new wiki content is -- changed, it triggers a job to make the preview. The preview job uses the -- <tt>wkhtmotoimage</tt> external program to make the preview image. package AWA.Wikis.Previews is -- The name under which the module is registered. NAME : constant String := "wiki-previews"; -- The worker procedure that performs the preview job. procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class); -- Preview job definition. package Preview_Job_Definition is new AWA.Jobs.Services.Work_Definition (Preview_Worker'Access); -- ------------------------------ -- Preview wiki module -- ------------------------------ type Preview_Module is new AWA.Modules.Module and AWA.Wikis.Modules.Wiki_Lifecycle.Listener with private; type Preview_Module_Access is access all Preview_Module'Class; -- Initialize the preview wiki module. overriding procedure Initialize (Plugin : in out Preview_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page. overriding procedure On_Create (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page. overriding procedure On_Update (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page. overriding procedure On_Delete (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Create a preview job and schedule the job to generate a new thumbnail preview for the page. procedure Make_Preview_Job (Plugin : in Preview_Module; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class); private type Preview_Module is new AWA.Modules.Module and AWA.Wikis.Modules.Wiki_Lifecycle.Listener with record Job_Module : AWA.Jobs.Modules.Job_Module_Access; end record; end AWA.Wikis.Previews;
----------------------------------------------------------------------- -- awa-wikis-previews -- Wiki preview management -- 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 EL.Expressions; with ASF.Applications; with AWA.Modules; with AWA.Jobs.Services; with AWA.Jobs.Modules; with AWA.Wikis.Modules; with AWA.Wikis.Models; -- == Wiki Preview Module == -- The <tt>AWA.Wikis.Previews</tt> package implements a preview image generation for a wiki page. -- This module is optional, it is possible to use the wikis without preview support. When the -- module is registered, it listens to wiki page lifecycle events. When a new wiki content is -- changed, it triggers a job to make the preview. The preview job uses the -- <tt>wkhtmotoimage</tt> external program to make the preview image. package AWA.Wikis.Previews is -- The name under which the module is registered. NAME : constant String := "wiki-previews"; -- The configuration parameter that defines how to build the wiki preview template path. PARAM_PREVIEW_TEMPLATE : constant String := "wiki.preview.template"; -- The configuration parameter to build the preview command to execute. PARAM_PREVIEW_COMMAND : constant String := "wiki.preview.command"; -- The worker procedure that performs the preview job. procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class); -- Preview job definition. package Preview_Job_Definition is new AWA.Jobs.Services.Work_Definition (Preview_Worker'Access); -- ------------------------------ -- Preview wiki module -- ------------------------------ type Preview_Module is new AWA.Modules.Module and AWA.Wikis.Modules.Wiki_Lifecycle.Listener with private; type Preview_Module_Access is access all Preview_Module'Class; -- Initialize the preview wiki module. overriding procedure Initialize (Plugin : in out Preview_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page. overriding procedure On_Create (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page. overriding procedure On_Update (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page. overriding procedure On_Delete (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Create a preview job and schedule the job to generate a new thumbnail preview for the page. procedure Make_Preview_Job (Plugin : in Preview_Module; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class); private type Preview_Module is new AWA.Modules.Module and AWA.Wikis.Modules.Wiki_Lifecycle.Listener with record Template : EL.Expressions.Expression; Command : EL.Expressions.Expression; Job_Module : AWA.Jobs.Modules.Job_Module_Access; end record; end AWA.Wikis.Previews;
Define PARAM_PREVIEW_TEMPLATE and PARAM_PREVIEW_COMMAND
Define PARAM_PREVIEW_TEMPLATE and PARAM_PREVIEW_COMMAND
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
7326eb9902f7be641486c6f1f9c7b48d2f3825f9
src/util-dates.ads
src/util-dates.ads
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Calendar.Formatting; with Ada.Calendar.Arithmetic; with Ada.Calendar.Time_Zones; -- = Date Utilities = -- The `Util.Dates` package provides various date utilities to help in formatting and parsing -- dates in various standard formats. It completes the standard `Ada.Calendar.Formatting` and -- other packages by implementing specific formatting and parsing. -- -- == Date Operations == -- Several operations allow to compute from a given date: -- -- * `Get_Day_Start`: The start of the day (0:00), -- * `Get_Day_End`: The end of the day (23:59:59), -- * `Get_Week_Start`: The start of the week, -- * `Get_Week_End`: The end of the week, -- * `Get_Month_Start`: The start of the month, -- * `Get_Month_End`: The end of the month -- -- The `Date_Record` type represents a date in a split format allowing -- to access easily the day, month, hour and other information. -- -- Now : Ada.Calendar.Time := Ada.Calendar.Clock; -- Week_Start : Ada.Calendar.Time := Get_Week_Start (Now); -- Week_End : Ada.Calendar.Time := Get_Week_End (Now); -- -- @include util-dates-rfc7231.ads -- @include util-dates-iso8601.ads -- @include util-dates-formats.ads package Util.Dates is -- The Unix equivalent of 'struct tm'. type Date_Record is record Date : Ada.Calendar.Time; Year : Ada.Calendar.Year_Number := 1901; Month : Ada.Calendar.Month_Number := 1; Month_Day : Ada.Calendar.Day_Number := 1; Day : Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Tuesday; Hour : Ada.Calendar.Formatting.Hour_Number := 0; Minute : Ada.Calendar.Formatting.Minute_Number := 0; Second : Ada.Calendar.Formatting.Second_Number := 0; Sub_Second : Ada.Calendar.Formatting.Second_Duration := 0.0; Time_Zone : Ada.Calendar.Time_Zones.Time_Offset := 0; Leap_Second : Boolean := False; end record; -- Split the date into a date record (See Ada.Calendar.Formatting.Split). procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0); -- Returns true if the given year is a leap year. function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean; -- Get the number of days in the given year. function Get_Day_Count (Year : in Ada.Calendar.Year_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get the number of days in the given month. function Get_Day_Count (Year : in Ada.Calendar.Year_Number; Month : in Ada.Calendar.Month_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get a time representing the given date at 00:00:00. function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the given date at 23:59:59. function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the week at 00:00:00. function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the week at 23:59:99. function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the month at 00:00:00. function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the month at 23:59:59. function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; end Util.Dates;
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Calendar.Formatting; with Ada.Calendar.Arithmetic; with Ada.Calendar.Time_Zones; -- = Date Utilities = -- The `Util.Dates` package provides various date utilities to help in formatting and parsing -- dates in various standard formats. It completes the standard `Ada.Calendar.Formatting` and -- other packages by implementing specific formatting and parsing. -- -- == Date Operations == -- Several operations allow to compute from a given date: -- -- * `Get_Day_Start`: The start of the day (0:00), -- * `Get_Day_End`: The end of the day (23:59:59), -- * `Get_Week_Start`: The start of the week, -- * `Get_Week_End`: The end of the week, -- * `Get_Month_Start`: The start of the month, -- * `Get_Month_End`: The end of the month -- -- The `Date_Record` type represents a date in a split format allowing -- to access easily the day, month, hour and other information. -- -- Now : Ada.Calendar.Time := Ada.Calendar.Clock; -- Week_Start : Ada.Calendar.Time := Get_Week_Start (Now); -- Week_End : Ada.Calendar.Time := Get_Week_End (Now); -- -- @include util-dates-rfc7231.ads -- @include util-dates-iso8601.ads -- @include util-dates-formats.ads package Util.Dates is -- The Unix equivalent of 'struct tm'. type Date_Record is record Date : Ada.Calendar.Time; Year : Ada.Calendar.Year_Number := 1901; Month : Ada.Calendar.Month_Number := 1; Month_Day : Ada.Calendar.Day_Number := 1; Day : Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Tuesday; Hour : Ada.Calendar.Formatting.Hour_Number := 0; Minute : Ada.Calendar.Formatting.Minute_Number := 0; Second : Ada.Calendar.Formatting.Second_Number := 0; Sub_Second : Ada.Calendar.Formatting.Second_Duration := 0.0; Time_Zone : Ada.Calendar.Time_Zones.Time_Offset := 0; Leap_Second : Boolean := False; end record; -- Split the date into a date record (See Ada.Calendar.Formatting.Split). procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0); -- Return the date from the date record (See Ada.Calendar.Formatting.Time_Of). function Time_Of (Date : in Date_Record) return Ada.Calendar.Time; -- Returns true if the given year is a leap year. function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean; -- Get the number of days in the given year. function Get_Day_Count (Year : in Ada.Calendar.Year_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get the number of days in the given month. function Get_Day_Count (Year : in Ada.Calendar.Year_Number; Month : in Ada.Calendar.Month_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get a time representing the given date at 00:00:00. function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the given date at 23:59:59. function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the week at 00:00:00. function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the week at 23:59:99. function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the month at 00:00:00. function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the month at 23:59:59. function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; end Util.Dates;
Declare Time_Of function to convert a Date_Record into a Time
Declare Time_Of function to convert a Date_Record into a Time
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2a1bc8a31b46a02ee16b97ef39afa053b91ce345
src/util-streams-texts.adb
src/util-streams-texts.adb
----------------------------------------------------------------------- -- Util.Streams.Files -- File Stream utilities -- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Texts is procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access) is begin Stream.Initialize (Output => To, Input => null, Size => 4096); end Initialize; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write (Ada.Strings.Unbounded.To_String (Item)); end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Buffered_Stream'Class) return String is use Ada.Streams; Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access) is begin Stream.Initialize (Output => null, Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Read_Line; end Util.Streams.Texts;
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; package body Util.Streams.Texts is use Ada.Streams; subtype Offset is Ada.Streams.Stream_Element_Offset; procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access) is begin Stream.Initialize (Output => To, Input => null, Size => 4096); end Initialize; -- ------------------------------ -- Write a raw character on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Char : in Character) is Buf : constant Ada.Streams.Stream_Element_Array (1 .. 1) := (1 => Ada.Streams.Stream_Element (Character'Pos (Char))); begin Stream.Write (Buf); end Write; -- ------------------------------ -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. -- ------------------------------ procedure Write_Wide (Stream : in out Print_Stream; Item : in Wide_Wide_Character) is use Interfaces; Val : Unsigned_32; Buf : Ada.Streams.Stream_Element_Array (1 .. 4); begin -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Val := Wide_Wide_Character'Pos (Item); if Val <= 16#7f# then Buf (1) := Ada.Streams.Stream_Element (Val); Stream.Write (Buf (1 .. 1)); elsif Val <= 16#07FF# then Buf (1) := Stream_Element (16#C0# or Shift_Right (Val, 6)); Buf (2) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 2)); elsif Val <= 16#0FFFF# then Buf (1) := Stream_Element (16#E0# or Shift_Right (Val, 12)); Val := Val and 16#0FFF#; Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 6)); Buf (3) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 3)); else Val := Val and 16#1FFFFF#; Buf (1) := Stream_Element (16#F0# or Shift_Right (Val, 18)); Val := Val and 16#3FFFF#; Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 12)); Val := Val and 16#0FFF#; Buf (3) := Stream_Element (16#80# or Shift_Right (Val, 6)); Buf (4) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 4)); end if; end Write_Wide; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in String) is Buf : Ada.Streams.Stream_Element_Array (Offset (Item'First) .. Offset (Item'Last)); for Buf'Address use Item'Address; begin Stream.Write (Buf); end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C))); end loop; end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Buffered_Stream'Class) return String is Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access) is begin Stream.Initialize (Output => null, Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Read_Line; end Util.Streams.Texts;
Refactor Buffered_Stream and Print_Stream - move character related Write operation to the Texts package (Print_Stream)
Refactor Buffered_Stream and Print_Stream - move character related Write operation to the Texts package (Print_Stream)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6dec824623eeba6130d0f2d8f276a4f40852994d
mat/src/mat-consoles.ads
mat/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - Console interface -- 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; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_THREAD, F_COUNT); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
Define new fields for the threads command
Define new fields for the threads command
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
3e869111276867b28656ad39f652886ce02531ce
src/gen-artifacts-yaml.adb
src/gen-artifacts-yaml.adb
----------------------------------------------------------------------- -- gen-artifacts-yaml -- Query artifact for Code Generator -- 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 Ada.Exceptions; with Ada.Text_IO; with Util.Strings; with Util.Beans.Objects; with Text; with Yaml.Source.File; with Yaml.Parser; with Gen.Configs; with Gen.Model.Tables; with Gen.Model.Mappings; with Util.Log.Loggers; with Util.Stacks; use Yaml; package body Gen.Artifacts.Yaml is function To_String (S : Ada.Strings.Unbounded.Unbounded_String) return String renames Ada.Strings.Unbounded.To_String; use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Configs; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Yaml"); type State_Type is (IN_ROOT, IN_TABLE, IN_COLUMNS, IN_KEYS, IN_COLUMN, IN_KEY, IN_UNKOWN); type Node_Info is record State : State_Type := IN_UNKOWN; Name : Text.Reference; Has_Name : Boolean := False; Table : Gen.Model.Tables.Table_Definition_Access; Col : Gen.Model.Tables.Column_Definition_Access; end record; type Node_Info_Access is access all Node_Info; package Node_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); procedure Process_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Stack : in out Node_Stack.Stack); procedure Read_Scalar (Node : in Node_Info_Access; Name : in String; Value : in String); procedure Read_Scalar (Node : in Node_Info_Access; Name : in String; Value : in String) is begin case Node.State is when IN_TABLE => if Node.Table = null then return; end if; Log.Debug ("Set table {0} attribute {1}={2}", Node.Table.Name, Name, Value); if Name = "table" then Node.Table.Table_Name := To_Unbounded_String (Value); elsif Name = "description" or Name = "comment" then Node.Table.Set_Comment (Value); end if; when IN_COLUMN | IN_KEY => if Node.Col = null then return; end if; Log.Debug ("Set table column {0} attribute {1}={2}", Node.Col.Name, Name, Value); if Name = "type" then Node.Col.Set_Type (Value); elsif Name = "length" then Node.Col.Sql_Length := Natural'Value (Value); elsif Name = "column" then Node.Col.Sql_Name := To_Unbounded_String (Value); elsif Name = "unique" then Node.Col.Unique := Value = "true" or Value = "yes"; elsif Name = "nullable" or Name = "optional" then Node.Col.Not_Null := Value = "false" or Value = "no"; elsif Name = "not-null" or Name = "required" then Node.Col.Not_Null := Value = "true" or Value = "yes"; elsif Name = "description" or Name = "comment" then Node.Col.Set_Comment (Value); end if; when others => Log.Error ("Scalar {0}: {1} not handled", Name, Value); end case; end Read_Scalar; procedure Process_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Stack : in out Node_Stack.Stack) is Node : Node_Info_Access; New_Node : Node_Info_Access; begin Node := Node_Stack.Current (Stack); if Node.Has_Name then Node.Has_Name := False; case Node.State is when IN_ROOT => Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Gen.Model.Tables.Create_Table (Node.Name); New_Node.State := IN_TABLE; Model.Register_Table (New_Node.Table); when IN_TABLE => if Node.Name = "fields" or Node.Name = "properties" then Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_COLUMNS; elsif Node.Name = "id" then Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_KEYS; else Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_TABLE; end if; when IN_COLUMNS => Node.Table.Add_Column (Node.Name, Node.Col); Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_COLUMN; when IN_KEYS => Node.Table.Add_Column (Node.Name, Node.Col); Node.Col.Is_Key := True; Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_KEY; when others => Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.State := IN_UNKOWN; end case; else Node_Stack.Push (Stack); end if; end Process_Mapping; -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Model : in out Gen.Model.Packages.Model_Definition; Context : in out Generator'Class) is pragma Unreferenced (Handler); Input : Source.Pointer; P : Parser.Instance; Cur : Event; Stack : Node_Stack.Stack; Node : Node_Info_Access; Loc : Mark; begin Log.Info ("Reading YAML file {0}", File); Input := Source.File.As_Source (File); P.Set_Input (Input); loop Cur := P.Next; exit when Cur.Kind = Stream_End; case Cur.Kind is when Stream_Start | Document_Start => Node_Stack.Push (Stack); Node := Node_Stack.Current (Stack); Node.State := IN_ROOT; when Stream_End | Document_End => Node_Stack.Pop (Stack); when Alias => null; when Scalar => Node := Node_Stack.Current (Stack); if Node.Has_Name then Read_Scalar (Node, To_String (Node.Name), To_String (Cur.Content)); Node.Has_Name := False; else Node.Name := Cur.Content; Node.Has_Name := True; end if; when Sequence_Start => Node_Stack.Push (Stack); when Sequence_End => Node_Stack.Pop (Stack); when Mapping_Start => Process_Mapping (Model, Stack); when Mapping_End => Node_Stack.Pop (Stack); when Annotation_Start => null; when Annotation_End => null; end case; end loop; exception when E : others => Loc := P.Current_Lexer_Token_Start; Context.Error ("{0}: {1}", Util.Strings.Image (Loc.Line) & ":" & Util.Strings.Image (Loc.Column) & ": ", Ada.Exceptions.Exception_Message (E)); end Read_Model; -- ------------------------------ -- Save the model in a YAML file. -- ------------------------------ procedure Save_Model (Handler : in Artifact; Path : in String; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Write_Description (Comment : in Util.Beans.Objects.Object; Indent : in Ada.Text_IO.Count); File : Ada.Text_IO.File_Type; -- Write a description field taking into account multi-lines. procedure Write_Description (Comment : in Util.Beans.Objects.Object; Indent : in Ada.Text_IO.Count) is use type Ada.Text_IO.Count; Content : constant String := Util.Beans.Objects.To_String (Comment); Pos, Start : Positive := Content'First; begin Ada.Text_IO.Set_Col (File, Indent); Ada.Text_IO.Put (File, "description: "); if Util.Strings.Index (Content, ASCII.LF) > 0 or Util.Strings.Index (Content, ASCII.CR) > 0 then Start := Content'First; Pos := Content'First; Ada.Text_IO.Put_Line (File, "|"); while Pos <= Content'Last loop if Content (Pos) = ASCII.CR or Content (Pos) = ASCII.LF then Ada.Text_IO.Set_Col (File, Indent + 2); Ada.Text_IO.Put_Line (File, Content (Start .. Pos - 1)); Start := Pos + 1; end if; Pos := Pos + 1; end loop; if Start < Pos then Ada.Text_IO.Set_Col (File, Indent + 2); Ada.Text_IO.Put_Line (File, Content (Start .. Pos - 1)); end if; else Ada.Text_IO.Put (File, Content); end if; Ada.Text_IO.New_Line (File); end Write_Description; procedure Write_Field (Item : in out Gen.Model.Definition'Class; Name : in String) is Value : constant Util.Beans.Objects.Object := Item.Get_Value (Name); begin Ada.Text_IO.Put_Line (File, Util.Beans.Objects.To_String (Value)); end Write_Field; procedure Process_Table (Table : in out Gen.Model.Tables.Table_Definition) is Iter : Gen.Model.Tables.Column_List.Cursor := Table.Members.First; Col : Gen.Model.Tables.Column_Definition_Access; begin Ada.Text_IO.Put (File, Table.Get_Name); Ada.Text_IO.Put_Line (File, ":"); Ada.Text_IO.Put_Line (File, " type: entity"); Ada.Text_IO.Put (File, " table: "); Write_Field (Table, "sqlName"); Ada.Text_IO.Put (File, " schema: "); Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, " readOnly: "); Ada.Text_IO.New_Line (File); Write_Description (Table.Comment, 3); Ada.Text_IO.Put (File, " indexes: "); Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, " id: "); Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, " fields: "); Ada.Text_IO.New_Line (File); for Col of Table.Members loop Ada.Text_IO.Put (File, " "); Ada.Text_IO.Put (File, Col.Get_Name); Ada.Text_IO.Put_Line (File, ":"); Ada.Text_IO.Put (File, " type: "); Ada.Text_IO.Put (File, Col.Get_Type); Ada.Text_IO.New_Line (File); if Col.Length > 0 then Ada.Text_IO.Put (File, " length:"); Ada.Text_IO.Put_Line (File, Positive'Image (Col.Length)); Ada.Text_IO.New_Line (File); end if; Ada.Text_IO.Put (File, " column: "); Write_Field (Col.all, "sqlName"); Ada.Text_IO.Put (File, " not-null: "); Ada.Text_IO.Put_Line (File, (if Col.Not_Null then "true" else "false")); Ada.Text_IO.Put (File, " unique: "); Ada.Text_IO.Put_Line (File, (if Col.Unique then "true" else "false")); Write_Description (Col.Comment, 5); Gen.Model.Tables.Column_List.Next (Iter); end loop; end Process_Table; begin Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, Path); Model.Iterate_Tables (Process_Table'Access); Ada.Text_IO.Close (File); end Save_Model; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is pragma Unreferenced (Handler); Iter : Gen.Model.Packages.Package_Cursor; Pkg : Gen.Model.Packages.Package_Definition_Access; begin Log.Debug ("Preparing the model for query"); Handler.Save_Model (Path => "model.yaml", Model => Model, Context => Context); -- -- Iter := Gen.Model.Packages.First (Model); -- while Gen.Model.Packages.Has_Element (Iter) loop -- Pkg := Gen.Model.Packages.Element (Iter); -- -- Gen.Model.Packages.Next (Iter); -- end loop; end Prepare; end Gen.Artifacts.Yaml;
----------------------------------------------------------------------- -- gen-artifacts-yaml -- Query artifact for Code Generator -- 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 Ada.Exceptions; with Ada.Text_IO; with Util.Strings; with Util.Beans.Objects; with Text; with Yaml.Source.File; with Yaml.Parser; with Gen.Configs; with Gen.Model.Tables; with Gen.Model.Mappings; with Util.Log.Loggers; with Util.Stacks; use Yaml; package body Gen.Artifacts.Yaml is function To_String (S : Ada.Strings.Unbounded.Unbounded_String) return String renames Ada.Strings.Unbounded.To_String; use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Configs; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Yaml"); type State_Type is (IN_ROOT, IN_TABLE, IN_COLUMNS, IN_KEYS, IN_COLUMN, IN_KEY, IN_UNKOWN); type Node_Info is record State : State_Type := IN_UNKOWN; Name : Text.Reference; Has_Name : Boolean := False; Table : Gen.Model.Tables.Table_Definition_Access; Col : Gen.Model.Tables.Column_Definition_Access; end record; type Node_Info_Access is access all Node_Info; package Node_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); procedure Process_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Stack : in out Node_Stack.Stack); procedure Read_Scalar (Node : in Node_Info_Access; Name : in String; Value : in String); procedure Read_Scalar (Node : in Node_Info_Access; Name : in String; Value : in String) is begin case Node.State is when IN_TABLE => if Node.Table = null then return; end if; Log.Debug ("Set table {0} attribute {1}={2}", Node.Table.Name, Name, Value); if Name = "table" then Node.Table.Table_Name := To_Unbounded_String (Value); elsif Name = "description" or Name = "comment" then Node.Table.Set_Comment (Value); end if; when IN_COLUMN | IN_KEY => if Node.Col = null then return; end if; Log.Debug ("Set table column {0} attribute {1}={2}", Node.Col.Name, Name, Value); if Name = "type" then Node.Col.Set_Type (Value); elsif Name = "length" then Node.Col.Sql_Length := Natural'Value (Value); elsif Name = "column" then Node.Col.Sql_Name := To_Unbounded_String (Value); elsif Name = "unique" then Node.Col.Unique := Value = "true" or Value = "yes"; elsif Name = "nullable" or Name = "optional" then Node.Col.Not_Null := Value = "false" or Value = "no"; elsif Name = "not-null" or Name = "required" then Node.Col.Not_Null := Value = "true" or Value = "yes"; elsif Name = "description" or Name = "comment" then Node.Col.Set_Comment (Value); end if; when others => Log.Error ("Scalar {0}: {1} not handled", Name, Value); end case; end Read_Scalar; procedure Process_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Stack : in out Node_Stack.Stack) is Node : Node_Info_Access; New_Node : Node_Info_Access; begin Node := Node_Stack.Current (Stack); if Node.Has_Name then Node.Has_Name := False; case Node.State is when IN_ROOT => Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Gen.Model.Tables.Create_Table (Node.Name); New_Node.State := IN_TABLE; Model.Register_Table (New_Node.Table); when IN_TABLE => if Node.Name = "fields" or Node.Name = "properties" then Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_COLUMNS; elsif Node.Name = "id" then Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_KEYS; else Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_TABLE; end if; when IN_COLUMNS => Node.Table.Add_Column (Node.Name, Node.Col); Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_COLUMN; when IN_KEYS => Node.Table.Add_Column (Node.Name, Node.Col); Node.Col.Is_Key := True; Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_KEY; when others => Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.State := IN_UNKOWN; end case; else Node_Stack.Push (Stack); end if; end Process_Mapping; -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Model : in out Gen.Model.Packages.Model_Definition; Context : in out Generator'Class) is pragma Unreferenced (Handler); Input : Source.Pointer; P : Parser.Instance; Cur : Event; Stack : Node_Stack.Stack; Node : Node_Info_Access; Loc : Mark; begin Log.Info ("Reading YAML file {0}", File); Input := Source.File.As_Source (File); P.Set_Input (Input); loop Cur := P.Next; exit when Cur.Kind = Stream_End; case Cur.Kind is when Stream_Start | Document_Start => Node_Stack.Push (Stack); Node := Node_Stack.Current (Stack); Node.State := IN_ROOT; when Stream_End | Document_End => Node_Stack.Pop (Stack); when Alias => null; when Scalar => Node := Node_Stack.Current (Stack); if Node.Has_Name then Read_Scalar (Node, To_String (Node.Name), To_String (Cur.Content)); Node.Has_Name := False; else Node.Name := Cur.Content; Node.Has_Name := True; end if; when Sequence_Start => Node_Stack.Push (Stack); when Sequence_End => Node_Stack.Pop (Stack); when Mapping_Start => Process_Mapping (Model, Stack); when Mapping_End => Node_Stack.Pop (Stack); when Annotation_Start => null; when Annotation_End => null; end case; end loop; exception when E : others => Loc := P.Current_Lexer_Token_Start; Context.Error ("{0}: {1}", Util.Strings.Image (Loc.Line) & ":" & Util.Strings.Image (Loc.Column) & ": ", Ada.Exceptions.Exception_Message (E)); end Read_Model; -- ------------------------------ -- Save the model in a YAML file. -- ------------------------------ procedure Save_Model (Handler : in Artifact; Path : in String; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Write_Description (Comment : in Util.Beans.Objects.Object; Indent : in Ada.Text_IO.Count); File : Ada.Text_IO.File_Type; -- Write a description field taking into account multi-lines. procedure Write_Description (Comment : in Util.Beans.Objects.Object; Indent : in Ada.Text_IO.Count) is use type Ada.Text_IO.Count; Content : constant String := Util.Beans.Objects.To_String (Comment); Pos, Start : Positive := Content'First; begin Ada.Text_IO.Set_Col (File, Indent); Ada.Text_IO.Put (File, "description: "); if Util.Strings.Index (Content, ASCII.LF) > 0 or Util.Strings.Index (Content, ASCII.CR) > 0 then Start := Content'First; Pos := Content'First; Ada.Text_IO.Put_Line (File, "|"); while Pos <= Content'Last loop if Content (Pos) = ASCII.CR or Content (Pos) = ASCII.LF then Ada.Text_IO.Set_Col (File, Indent + 2); Ada.Text_IO.Put_Line (File, Content (Start .. Pos - 1)); Start := Pos + 1; end if; Pos := Pos + 1; end loop; if Start < Pos then Ada.Text_IO.Set_Col (File, Indent + 2); Ada.Text_IO.Put_Line (File, Content (Start .. Pos - 1)); end if; else Ada.Text_IO.Put (File, Content); end if; Ada.Text_IO.New_Line (File); end Write_Description; procedure Write_Field (Item : in Gen.Model.Definition'Class; Name : in String) is Value : constant Util.Beans.Objects.Object := Item.Get_Value (Name); begin Ada.Text_IO.Put_Line (File, Util.Beans.Objects.To_String (Value)); end Write_Field; procedure Write_Column (Col : in Gen.Model.Tables.Column_Definition'Class) is Col_Type : Gen.Model.Mappings.Mapping_Definition_Access; begin Col_Type := Col.Get_Type_Mapping; Ada.Text_IO.Put (File, " "); Ada.Text_IO.Put (File, Col.Get_Name); Ada.Text_IO.Put_Line (File, ":"); Ada.Text_IO.Put (File, " type: "); Ada.Text_IO.Put (File, Ada.Strings.Unbounded.To_String (Col_Type.Name)); Ada.Text_IO.New_Line (File); if Col.Is_Variable_Length then Ada.Text_IO.Put (File, " length:"); Ada.Text_IO.Put_Line (File, Positive'Image (Col.Sql_Length)); end if; Ada.Text_IO.Put (File, " column: "); Write_Field (Col, "sqlName"); if Col_Type.Nullable then Ada.Text_IO.Put_Line (File, " nullable: true"); end if; Ada.Text_IO.Put (File, " not-null: "); Ada.Text_IO.Put_Line (File, (if Col.Not_Null then "true" else "false")); if Col.Is_Version then Ada.Text_IO.Put_Line (File, " version: true"); end if; if not Col.Is_Updated then Ada.Text_IO.Put_Line (File, " readonly: true"); end if; if Col.Is_Auditable then Ada.Text_IO.Put_Line (File, " auditable: true"); end if; Ada.Text_IO.Put (File, " unique: "); Ada.Text_IO.Put_Line (File, (if Col.Unique then "true" else "false")); Write_Description (Col.Get_Comment, 7); end Write_Column; procedure Process_Table (Table : in out Gen.Model.Tables.Table_Definition) is Iter : Gen.Model.Tables.Column_List.Cursor := Table.Members.First; Col : Gen.Model.Tables.Column_Definition_Access; begin Ada.Text_IO.Put (File, Table.Get_Name); Ada.Text_IO.Put_Line (File, ":"); Ada.Text_IO.Put_Line (File, " type: entity"); Ada.Text_IO.Put (File, " table: "); Write_Field (Table, "sqlName"); Write_Description (Table.Get_Comment, 3); Ada.Text_IO.Put (File, " indexes: "); Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, " id: "); Ada.Text_IO.New_Line (File); for Col of Table.Members loop if Col.Is_Key then Write_Column (Col.all); end if; end loop; Ada.Text_IO.Put (File, " fields: "); Ada.Text_IO.New_Line (File); for Col of Table.Members loop if not Col.Is_Key then Write_Column (Col.all); end if; end loop; end Process_Table; begin Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, Path); Model.Iterate_Tables (Process_Table'Access); Ada.Text_IO.Close (File); end Save_Model; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is Iter : Gen.Model.Packages.Package_Cursor; Pkg : Gen.Model.Packages.Package_Definition_Access; begin Log.Debug ("Preparing the model for query"); Handler.Save_Model (Path => "model.yaml", Model => Model, Context => Context); -- -- Iter := Gen.Model.Packages.First (Model); -- while Gen.Model.Packages.Has_Element (Iter) loop -- Pkg := Gen.Model.Packages.Element (Iter); -- -- Gen.Model.Packages.Next (Iter); -- end loop; end Prepare; end Gen.Artifacts.Yaml;
Update the generation of YAML model files - generate full column definition, - remove unused fields
Update the generation of YAML model files - generate full column definition, - remove unused fields
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
798f172d13992bfd6d10ddb0ce15b1412fac3e01
src/gen-artifacts-yaml.adb
src/gen-artifacts-yaml.adb
----------------------------------------------------------------------- -- gen-artifacts-yaml -- Query artifact for Code Generator -- 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 Ada.Exceptions; with Ada.Text_IO; with Util.Strings; with Util.Beans.Objects; with Text; with Yaml.Source.File; with Yaml.Parser; with Gen.Configs; with Gen.Model.Tables; with Gen.Model.Mappings; with Util.Log.Loggers; with Util.Stacks; use Yaml; package body Gen.Artifacts.Yaml is function To_String (S : Ada.Strings.Unbounded.Unbounded_String) return String renames Ada.Strings.Unbounded.To_String; use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Configs; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Yaml"); type State_Type is (IN_ROOT, IN_TABLE, IN_COLUMNS, IN_KEYS, IN_COLUMN, IN_KEY, IN_UNKOWN); type Node_Info is record State : State_Type := IN_UNKOWN; Name : Text.Reference; Has_Name : Boolean := False; Table : Gen.Model.Tables.Table_Definition_Access; Col : Gen.Model.Tables.Column_Definition_Access; end record; type Node_Info_Access is access all Node_Info; package Node_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); procedure Process_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Stack : in out Node_Stack.Stack; File : in String; Loc : in Mark); procedure Read_Scalar (Node : in Node_Info_Access; Name : in String; Value : in String); procedure Read_Scalar (Node : in Node_Info_Access; Name : in String; Value : in String) is begin case Node.State is when IN_TABLE => if Node.Table = null then return; end if; Log.Debug ("Set table {0} attribute {1}={2}", Node.Table.Name, Name, Value); if Name = "table" then Node.Table.Table_Name := To_Unbounded_String (Value); elsif Name = "description" or Name = "comment" then Node.Table.Set_Comment (Value); end if; when IN_COLUMN | IN_KEY => if Node.Col = null then return; end if; Log.Debug ("Set table column {0} attribute {1}={2}", Node.Col.Name, Name, Value); if Name = "type" then Node.Col.Set_Type (Value); elsif Name = "length" then Node.Col.Sql_Length := Natural'Value (Value); elsif Name = "column" then Node.Col.Sql_Name := To_Unbounded_String (Value); elsif Name = "unique" then Node.Col.Unique := Value = "true" or Value = "yes"; elsif Name = "nullable" or Name = "optional" then Node.Col.Not_Null := Value = "false" or Value = "no"; elsif Name = "not-null" or Name = "required" then Node.Col.Not_Null := Value = "true" or Value = "yes"; elsif Name = "description" or Name = "comment" then Node.Col.Set_Comment (Value); end if; when others => Log.Error ("Scalar {0}: {1} not handled", Name, Value); end case; end Read_Scalar; procedure Process_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Stack : in out Node_Stack.Stack; File : in String; Loc : in Mark) is function Location return String is (File & ":" & Util.Strings.Image (Loc.Line) & ":" & Util.Strings.Image (Loc.Column)); Node : Node_Info_Access; New_Node : Node_Info_Access; begin Node := Node_Stack.Current (Stack); if Node.Has_Name then Node.Has_Name := False; case Node.State is when IN_ROOT => Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Gen.Model.Tables.Create_Table (Node.Name); New_Node.Table.Set_Location (Location); New_Node.State := IN_TABLE; Model.Register_Table (New_Node.Table); when IN_TABLE => if Node.Name = "fields" or Node.Name = "properties" then Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_COLUMNS; elsif Node.Name = "id" then Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_KEYS; else Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_TABLE; end if; when IN_COLUMNS => Node.Table.Add_Column (Node.Name, Node.Col); Node.Col.Set_Location (Location); Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_COLUMN; when IN_KEYS => Node.Table.Add_Column (Node.Name, Node.Col); Node.Col.Set_Location (Location); Node.Col.Is_Key := True; Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_KEY; when others => Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.State := IN_UNKOWN; end case; else Node_Stack.Push (Stack); end if; end Process_Mapping; -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Model : in out Gen.Model.Packages.Model_Definition; Context : in out Generator'Class) is pragma Unreferenced (Handler); Input : Source.Pointer; P : Parser.Instance; Cur : Event; Stack : Node_Stack.Stack; Node : Node_Info_Access; Loc : Mark; begin Log.Info ("Reading YAML file {0}", File); Input := Source.File.As_Source (File); P.Set_Input (Input); loop Cur := P.Next; exit when Cur.Kind = Stream_End; case Cur.Kind is when Stream_Start | Document_Start => Node_Stack.Push (Stack); Node := Node_Stack.Current (Stack); Node.State := IN_ROOT; when Stream_End | Document_End => Node_Stack.Pop (Stack); when Alias => null; when Scalar => Node := Node_Stack.Current (Stack); if Node.Has_Name then Read_Scalar (Node, To_String (Node.Name), To_String (Cur.Content)); Node.Has_Name := False; else Node.Name := Cur.Content; Node.Has_Name := True; end if; when Sequence_Start => Node_Stack.Push (Stack); when Sequence_End => Node_Stack.Pop (Stack); when Mapping_Start => Process_Mapping (Model, Stack, File, P.Current_Lexer_Token_Start); when Mapping_End => Node_Stack.Pop (Stack); when Annotation_Start => null; when Annotation_End => null; end case; end loop; exception when E : others => Loc := P.Current_Lexer_Token_Start; Context.Error ("{0}: {1}", Util.Strings.Image (Loc.Line) & ":" & Util.Strings.Image (Loc.Column) & ": ", Ada.Exceptions.Exception_Message (E)); end Read_Model; -- ------------------------------ -- Save the model in a YAML file. -- ------------------------------ procedure Save_Model (Handler : in Artifact; Path : in String; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Write_Description (Comment : in Util.Beans.Objects.Object; Indent : in Ada.Text_IO.Count); File : Ada.Text_IO.File_Type; -- Write a description field taking into account multi-lines. procedure Write_Description (Comment : in Util.Beans.Objects.Object; Indent : in Ada.Text_IO.Count) is use type Ada.Text_IO.Count; Content : constant String := Util.Beans.Objects.To_String (Comment); Pos, Start : Positive := Content'First; begin Ada.Text_IO.Set_Col (File, Indent); Ada.Text_IO.Put (File, "description: "); if Util.Strings.Index (Content, ASCII.LF) > 0 or Util.Strings.Index (Content, ASCII.CR) > 0 then Start := Content'First; Pos := Content'First; Ada.Text_IO.Put_Line (File, "|"); while Pos <= Content'Last loop if Content (Pos) = ASCII.CR or Content (Pos) = ASCII.LF then Ada.Text_IO.Set_Col (File, Indent + 2); Ada.Text_IO.Put_Line (File, Content (Start .. Pos - 1)); Start := Pos + 1; end if; Pos := Pos + 1; end loop; if Start < Pos then Ada.Text_IO.Set_Col (File, Indent + 2); Ada.Text_IO.Put_Line (File, Content (Start .. Pos - 1)); end if; else Ada.Text_IO.Put (File, Content); end if; Ada.Text_IO.New_Line (File); end Write_Description; procedure Write_Field (Item : in Gen.Model.Definition'Class; Name : in String) is Value : constant Util.Beans.Objects.Object := Item.Get_Value (Name); begin Ada.Text_IO.Put_Line (File, Util.Beans.Objects.To_String (Value)); end Write_Field; procedure Write_Column (Col : in Gen.Model.Tables.Column_Definition'Class) is use type Gen.Model.Mappings.Mapping_Definition_Access; Col_Type : Gen.Model.Mappings.Mapping_Definition_Access; begin Col_Type := Col.Get_Type_Mapping; Ada.Text_IO.Put (File, " "); Ada.Text_IO.Put (File, Col.Get_Name); Ada.Text_IO.Put_Line (File, ":"); Ada.Text_IO.Put (File, " type: "); if Col_Type /= null then Ada.Text_IO.Put (File, Ada.Strings.Unbounded.To_String (Col_Type.Name)); end if; Ada.Text_IO.New_Line (File); if Col.Is_Variable_Length then Ada.Text_IO.Put (File, " length:"); Ada.Text_IO.Put_Line (File, Positive'Image (Col.Sql_Length)); end if; Ada.Text_IO.Put (File, " column: "); Write_Field (Col, "sqlName"); if Col_Type /= null and then Col_Type.Nullable then Ada.Text_IO.Put_Line (File, " nullable: true"); end if; Ada.Text_IO.Put (File, " not-null: "); Ada.Text_IO.Put_Line (File, (if Col.Not_Null then "true" else "false")); if Col.Is_Version then Ada.Text_IO.Put_Line (File, " version: true"); end if; if not Col.Is_Updated then Ada.Text_IO.Put_Line (File, " readonly: true"); end if; if Col.Is_Auditable then Ada.Text_IO.Put_Line (File, " auditable: true"); end if; Ada.Text_IO.Put (File, " unique: "); Ada.Text_IO.Put_Line (File, (if Col.Unique then "true" else "false")); Write_Description (Col.Get_Comment, 7); end Write_Column; procedure Process_Table (Table : in out Gen.Model.Tables.Table_Definition) is Iter : Gen.Model.Tables.Column_List.Cursor := Table.Members.First; Col : Gen.Model.Tables.Column_Definition_Access; begin Ada.Text_IO.Put (File, Table.Get_Name); Ada.Text_IO.Put_Line (File, ":"); Ada.Text_IO.Put_Line (File, " type: entity"); Ada.Text_IO.Put (File, " table: "); Write_Field (Table, "sqlName"); Write_Description (Table.Get_Comment, 3); Ada.Text_IO.Put (File, " indexes: "); Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, " id: "); Ada.Text_IO.New_Line (File); for Col of Table.Members loop if Col.Is_Key then Write_Column (Col.all); end if; end loop; Ada.Text_IO.Put (File, " fields: "); Ada.Text_IO.New_Line (File); for Col of Table.Members loop if not Col.Is_Key then Write_Column (Col.all); end if; end loop; end Process_Table; begin Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, Path); Model.Iterate_Tables (Process_Table'Access); Ada.Text_IO.Close (File); end Save_Model; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is Iter : Gen.Model.Packages.Package_Cursor; Pkg : Gen.Model.Packages.Package_Definition_Access; begin Log.Debug ("Preparing the model for query"); Handler.Save_Model (Path => "model.yaml", Model => Model, Context => Context); -- -- Iter := Gen.Model.Packages.First (Model); -- while Gen.Model.Packages.Has_Element (Iter) loop -- Pkg := Gen.Model.Packages.Element (Iter); -- -- Gen.Model.Packages.Next (Iter); -- end loop; end Prepare; end Gen.Artifacts.Yaml;
----------------------------------------------------------------------- -- gen-artifacts-yaml -- Query artifact for Code Generator -- 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 Ada.Exceptions; with Ada.Text_IO; with Util.Strings; with Util.Beans.Objects; with Text; with Yaml.Source.File; with Yaml.Parser; with Gen.Configs; with Gen.Model.Tables; with Gen.Model.Mappings; with Util.Log.Loggers; with Util.Stacks; use Yaml; package body Gen.Artifacts.Yaml is function To_String (S : Ada.Strings.Unbounded.Unbounded_String) return String renames Ada.Strings.Unbounded.To_String; use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Configs; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Yaml"); type State_Type is (IN_ROOT, IN_TABLE, IN_COLUMNS, IN_KEYS, IN_COLUMN, IN_KEY, IN_UNKOWN); type Node_Info is record State : State_Type := IN_UNKOWN; Name : Text.Reference; Has_Name : Boolean := False; Table : Gen.Model.Tables.Table_Definition_Access; Col : Gen.Model.Tables.Column_Definition_Access; end record; type Node_Info_Access is access all Node_Info; package Node_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); procedure Process_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Stack : in out Node_Stack.Stack; File : in String; Loc : in Mark); procedure Read_Scalar (Node : in Node_Info_Access; Name : in String; Value : in String; Context : in out Generator'Class); procedure Read_Scalar (Node : in Node_Info_Access; Name : in String; Value : in String; Context : in out Generator'Class) is begin case Node.State is when IN_TABLE => if Node.Table = null then return; end if; Log.Debug ("Set table {0} attribute {1}={2}", Node.Table.Name, Name, Value); if Name = "table" then Node.Table.Table_Name := To_Unbounded_String (Value); elsif Name = "description" or Name = "comment" then Node.Table.Set_Comment (Value); end if; when IN_COLUMN | IN_KEY => if Node.Col = null then return; end if; Log.Debug ("Set table column {0} attribute {1}={2}", Node.Col.Name, Name, Value); if Name = "type" then Node.Col.Set_Type (Value); elsif Name = "length" then Node.Col.Set_Sql_Length (Value, Context); elsif Name = "column" then Node.Col.Sql_Name := To_Unbounded_String (Value); elsif Name = "unique" then Node.Col.Unique := Value = "true" or Value = "yes"; elsif Name = "nullable" or Name = "optional" then Node.Col.Not_Null := Value = "false" or Value = "no"; elsif Name = "not-null" or Name = "required" then Node.Col.Not_Null := Value = "true" or Value = "yes"; elsif Name = "description" or Name = "comment" then Node.Col.Set_Comment (Value); end if; when others => Log.Error ("Scalar {0}: {1} not handled", Name, Value); end case; end Read_Scalar; procedure Process_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Stack : in out Node_Stack.Stack; File : in String; Loc : in Mark) is function Location return String is (File & ":" & Util.Strings.Image (Loc.Line) & ":" & Util.Strings.Image (Loc.Column)); Node : Node_Info_Access; New_Node : Node_Info_Access; begin Node := Node_Stack.Current (Stack); if Node.Has_Name then Node.Has_Name := False; case Node.State is when IN_ROOT => Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Gen.Model.Tables.Create_Table (Node.Name); New_Node.Table.Set_Location (Location); New_Node.State := IN_TABLE; Model.Register_Table (New_Node.Table); when IN_TABLE => if Node.Name = "fields" or Node.Name = "properties" then Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_COLUMNS; elsif Node.Name = "id" then Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_KEYS; else Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_TABLE; end if; when IN_COLUMNS => Node.Table.Add_Column (Node.Name, Node.Col); Node.Col.Set_Location (Location); Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_COLUMN; when IN_KEYS => Node.Table.Add_Column (Node.Name, Node.Col); Node.Col.Set_Location (Location); Node.Col.Is_Key := True; Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.Table := Node.Table; New_Node.State := IN_KEY; when others => Node_Stack.Push (Stack); New_Node := Node_Stack.Current (Stack); New_Node.State := IN_UNKOWN; end case; else Node_Stack.Push (Stack); end if; end Process_Mapping; -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Model : in out Gen.Model.Packages.Model_Definition; Context : in out Generator'Class) is pragma Unreferenced (Handler); Input : Source.Pointer; P : Parser.Instance; Cur : Event; Stack : Node_Stack.Stack; Node : Node_Info_Access; Loc : Mark; begin Log.Info ("Reading YAML file {0}", File); Input := Source.File.As_Source (File); P.Set_Input (Input); loop Cur := P.Next; exit when Cur.Kind = Stream_End; case Cur.Kind is when Stream_Start | Document_Start => Node_Stack.Push (Stack); Node := Node_Stack.Current (Stack); Node.State := IN_ROOT; when Stream_End | Document_End => Node_Stack.Pop (Stack); when Alias => null; when Scalar => Node := Node_Stack.Current (Stack); if Node.Has_Name then Read_Scalar (Node, To_String (Node.Name), To_String (Cur.Content), Context); Node.Has_Name := False; else Node.Name := Cur.Content; Node.Has_Name := True; end if; when Sequence_Start => Node_Stack.Push (Stack); when Sequence_End => Node_Stack.Pop (Stack); when Mapping_Start => Process_Mapping (Model, Stack, File, P.Current_Lexer_Token_Start); when Mapping_End => Node_Stack.Pop (Stack); when Annotation_Start => null; when Annotation_End => null; end case; end loop; exception when E : others => Loc := P.Current_Lexer_Token_Start; Context.Error ("{0}: {1}", Util.Strings.Image (Loc.Line) & ":" & Util.Strings.Image (Loc.Column) & ": ", Ada.Exceptions.Exception_Message (E)); end Read_Model; -- ------------------------------ -- Save the model in a YAML file. -- ------------------------------ procedure Save_Model (Handler : in Artifact; Path : in String; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Write_Description (Comment : in Util.Beans.Objects.Object; Indent : in Ada.Text_IO.Count); File : Ada.Text_IO.File_Type; -- Write a description field taking into account multi-lines. procedure Write_Description (Comment : in Util.Beans.Objects.Object; Indent : in Ada.Text_IO.Count) is use type Ada.Text_IO.Count; Content : constant String := Util.Beans.Objects.To_String (Comment); Pos, Start : Positive := Content'First; begin Ada.Text_IO.Set_Col (File, Indent); Ada.Text_IO.Put (File, "description: "); if Util.Strings.Index (Content, ASCII.LF) > 0 or Util.Strings.Index (Content, ASCII.CR) > 0 then Start := Content'First; Pos := Content'First; Ada.Text_IO.Put_Line (File, "|"); while Pos <= Content'Last loop if Content (Pos) = ASCII.CR or Content (Pos) = ASCII.LF then Ada.Text_IO.Set_Col (File, Indent + 2); Ada.Text_IO.Put_Line (File, Content (Start .. Pos - 1)); Start := Pos + 1; end if; Pos := Pos + 1; end loop; if Start < Pos then Ada.Text_IO.Set_Col (File, Indent + 2); Ada.Text_IO.Put_Line (File, Content (Start .. Pos - 1)); end if; else Ada.Text_IO.Put (File, Content); end if; Ada.Text_IO.New_Line (File); end Write_Description; procedure Write_Field (Item : in Gen.Model.Definition'Class; Name : in String) is Value : constant Util.Beans.Objects.Object := Item.Get_Value (Name); begin Ada.Text_IO.Put_Line (File, Util.Beans.Objects.To_String (Value)); end Write_Field; procedure Write_Column (Col : in Gen.Model.Tables.Column_Definition'Class) is use type Gen.Model.Mappings.Mapping_Definition_Access; Col_Type : Gen.Model.Mappings.Mapping_Definition_Access; begin Col_Type := Col.Get_Type_Mapping; Ada.Text_IO.Put (File, " "); Ada.Text_IO.Put (File, Col.Get_Name); Ada.Text_IO.Put_Line (File, ":"); Ada.Text_IO.Put (File, " type: "); if Col_Type /= null then Ada.Text_IO.Put (File, Col_Type.Get_Type_Name); end if; Ada.Text_IO.New_Line (File); if Col.Is_Variable_Length then Ada.Text_IO.Put (File, " length:"); Ada.Text_IO.Put_Line (File, Positive'Image (Col.Sql_Length)); end if; Ada.Text_IO.Put (File, " column: "); Write_Field (Col, "sqlName"); if Col_Type /= null and then Col_Type.Nullable then Ada.Text_IO.Put_Line (File, " nullable: true"); end if; Ada.Text_IO.Put (File, " not-null: "); Ada.Text_IO.Put_Line (File, (if Col.Not_Null then "true" else "false")); if Col.Is_Version then Ada.Text_IO.Put_Line (File, " version: true"); end if; if not Col.Is_Updated then Ada.Text_IO.Put_Line (File, " readonly: true"); end if; if Col.Is_Auditable then Ada.Text_IO.Put_Line (File, " auditable: true"); end if; Ada.Text_IO.Put (File, " unique: "); Ada.Text_IO.Put_Line (File, (if Col.Unique then "true" else "false")); Write_Description (Col.Get_Comment, 7); end Write_Column; procedure Process_Table (Table : in out Gen.Model.Tables.Table_Definition) is Iter : Gen.Model.Tables.Column_List.Cursor := Table.Members.First; Col : Gen.Model.Tables.Column_Definition_Access; begin Ada.Text_IO.Put (File, Table.Get_Name); Ada.Text_IO.Put_Line (File, ":"); Ada.Text_IO.Put_Line (File, " type: entity"); Ada.Text_IO.Put (File, " table: "); Write_Field (Table, "sqlName"); Write_Description (Table.Get_Comment, 3); Ada.Text_IO.Put (File, " indexes: "); Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, " id: "); Ada.Text_IO.New_Line (File); for Col of Table.Members loop if Col.Is_Key then Write_Column (Col.all); end if; end loop; Ada.Text_IO.Put (File, " fields: "); Ada.Text_IO.New_Line (File); for Col of Table.Members loop if not Col.Is_Key then Write_Column (Col.all); end if; end loop; end Process_Table; begin Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, Path); Model.Iterate_Tables (Process_Table'Access); Ada.Text_IO.Close (File); end Save_Model; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is Iter : Gen.Model.Packages.Package_Cursor; Pkg : Gen.Model.Packages.Package_Definition_Access; begin Log.Debug ("Preparing the model for query"); Handler.Save_Model (Path => "model.yaml", Model => Model, Context => Context); -- -- Iter := Gen.Model.Packages.First (Model); -- while Gen.Model.Packages.Has_Element (Iter) loop -- Pkg := Gen.Model.Packages.Element (Iter); -- -- Gen.Model.Packages.Next (Iter); -- end loop; end Prepare; end Gen.Artifacts.Yaml;
Update to use Set_Sql_Length and Get_Type_Name operations
Update to use Set_Sql_Length and Get_Type_Name operations
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
c3f43d811f920edbd4e9e3677db49ad5c2b05511
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_Perm : 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 := new URLs.URL_Policy; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin_Perm := 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_Perm) := 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; 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 := new URLs.URL_Policy; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_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;
Rename the role Admin_Perm into Admin
Rename the role Admin_Perm into Admin
Ada
apache-2.0
stcarrez/ada-security
38175b3d99efab4fb13e3b1bc4f5ab7c29d8fc34
src/util-dates-iso8601.adb
src/util-dates-iso8601.adb
----------------------------------------------------------------------- -- util-dates-iso8601 -- ISO8601 dates -- Copyright (C) 2011, 2013, 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. ----------------------------------------------------------------------- package body Util.Dates.ISO8601 is -- ------------------------------ -- Parses an ISO8601 date and return it as a calendar time. -- Raises Constraint_Error if the date format is not recognized. -- ------------------------------ function Value (Date : in String) return Ada.Calendar.Time is use Ada.Calendar; use Ada.Calendar.Formatting; Result : Date_Record; Pos : Natural; begin if Date'Length < 4 then raise Constraint_Error with "Invalid date"; end if; Result.Hour := 0; Result.Minute := 0; Result.Second := 0; Result.Sub_Second := 0.0; Result.Time_Zone := 0; Result.Year := Year_Number'Value (Date (Date'First .. Date'First + 3)); if Date'Length = 4 then -- ISO8601 date: YYYY Result.Month := 1; Result.Month_Day := 1; elsif Date'Length = 7 and Date (Date'First + 4) = '-' then -- ISO8601 date: YYYY-MM Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'Last)); Result.Month_Day := 1; elsif Date'Length = 8 then -- ISO8601 date: YYYYMMDD Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'First + 5)); Result.Month_Day := Day_Number'Value (Date (Date'First + 6 .. Date'First + 7)); elsif Date'Length >= 9 and then Date (Date'First + 4) = '-' and then Date (Date'First + 7) = '-' then -- ISO8601 date: YYYY-MM-DD Result.Month := Month_Number'Value (Date (Date'First + 5 .. Date'First + 6)); Result.Month_Day := Day_Number'Value (Date (Date'First + 8 .. Date'First + 9)); -- ISO8601 date: YYYY-MM-DDTHH if Date'Length > 12 then if Date (Date'First + 10) /= 'T' then raise Constraint_Error with "invalid date"; end if; Result.Hour := Hour_Number'Value (Date (Date'First + 11 .. Date'First + 12)); Pos := Date'First + 13; end if; if Date'Length > 15 then if Date (Date'First + 13) /= ':' then raise Constraint_Error with "invalid date"; end if; Result.Minute := Minute_Number'Value (Date (Date'First + 14 .. Date'First + 15)); Pos := Date'First + 16; end if; if Date'Length > 18 then if Date (Date'First + 16) /= ':' then raise Constraint_Error with "invalid date"; end if; Result.Second := Second_Number'Value (Date (Date'First + 17 .. Date'First + 18)); Pos := Date'First + 19; end if; -- ISO8601 timezone: +hh:mm or -hh:mm -- if Date'Length > Pos + 4 then -- if Date (Pos) /= '+' and Date (Pos) /= '-' and Date (Pos + 2) /= ':' then -- raise Constraint_Error with "invalid date"; -- end if; -- end if; else raise Constraint_Error with "invalid date"; end if; return Ada.Calendar.Formatting.Time_Of (Year => Result.Year, Month => Result.Month, Day => Result.Month_Day, Hour => Result.Hour, Minute => Result.Minute, Second => Result.Second, Sub_Second => Result.Sub_Second, Time_Zone => Result.Time_Zone); end Value; -- ------------------------------ -- Return the ISO8601 date. -- ------------------------------ function Image (Date : in Ada.Calendar.Time) return String is D : Date_Record; begin Split (D, Date); return Image (D); end Image; function Image (Date : in Date_Record) return String is To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 10) := "0000-00-00"; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); return Result; end Image; function Image (Date : in Ada.Calendar.Time; Precision : in Precision_Type) return String is D : Date_Record; begin Split (D, Date); return Image (D, Precision); end Image; function Image (Date : in Date_Record; Precision : in Precision_Type) return String is use type Ada.Calendar.Time_Zones.Time_Offset; To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 29) := "0000-00-00T00:00:00.000-00:00"; N, Tz : Natural; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); if Precision = YEAR then return Result (1 .. 4); end if; Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); if Precision = MONTH then return Result (1 .. 7); end if; Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); if Precision = DAY then return Result (1 .. 10); end if; Result (12) := To_Char (Date.Hour / 10); Result (13) := To_Char (Date.Hour mod 10); if Precision = HOUR then return Result (1 .. 13); end if; Result (15) := To_Char (Date.Minute / 10); Result (16) := To_Char (Date.Minute mod 10); if Precision = MINUTE then return Result (1 .. 16); end if; Result (18) := To_Char (Date.Second / 10); Result (19) := To_Char (Date.Second mod 10); if Precision = SECOND then return Result (1 .. 19); end if; N := Natural (Date.Sub_Second * 1000.0); Result (21) := To_Char (N / 100); Result (22) := To_Char ((N mod 100) / 10); Result (23) := To_Char (N mod 10); if Date.Time_Zone < 0 then Tz := Natural (-Date.Time_Zone); else Result (24) := '+'; Tz := Natural (Date.Time_Zone); end if; Result (25) := To_Char (Tz / 600); Result (26) := To_Char ((Tz / 60) mod 10); Tz := Tz mod 60; Result (28) := To_Char (Tz / 10); Result (29) := To_Char (Tz mod 10); return Result; end Image; end Util.Dates.ISO8601;
----------------------------------------------------------------------- -- util-dates-iso8601 -- ISO8601 dates -- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Dates.ISO8601 is -- ------------------------------ -- Parses an ISO8601 date and return it as a calendar time. -- Raises Constraint_Error if the date format is not recognized. -- ------------------------------ function Value (Date : in String) return Ada.Calendar.Time is use Ada.Calendar; use Ada.Calendar.Formatting; Result : Date_Record; Pos : Natural; begin if Date'Length < 4 then raise Constraint_Error with "Invalid date"; end if; Result.Hour := 0; Result.Minute := 0; Result.Second := 0; Result.Sub_Second := 0.0; Result.Time_Zone := 0; Result.Year := Year_Number'Value (Date (Date'First .. Date'First + 3)); if Date'Length = 4 then -- ISO8601 date: YYYY Result.Month := 1; Result.Month_Day := 1; elsif Date'Length = 7 and Date (Date'First + 4) = '-' then -- ISO8601 date: YYYY-MM Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'Last)); Result.Month_Day := 1; elsif Date'Length = 8 then -- ISO8601 date: YYYYMMDD Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'First + 5)); Result.Month_Day := Day_Number'Value (Date (Date'First + 6 .. Date'First + 7)); elsif Date'Length >= 9 and then Date (Date'First + 4) = '-' and then Date (Date'First + 7) = '-' then -- ISO8601 date: YYYY-MM-DD Result.Month := Month_Number'Value (Date (Date'First + 5 .. Date'First + 6)); Result.Month_Day := Day_Number'Value (Date (Date'First + 8 .. Date'First + 9)); -- ISO8601 date: YYYY-MM-DDTHH if Date'Length > 12 then if Date (Date'First + 10) /= 'T' then raise Constraint_Error with "invalid date"; end if; Result.Hour := Hour_Number'Value (Date (Date'First + 11 .. Date'First + 12)); Pos := Date'First + 13; end if; if Date'Length > 15 then if Date (Date'First + 13) /= ':' then raise Constraint_Error with "invalid date"; end if; Result.Minute := Minute_Number'Value (Date (Date'First + 14 .. Date'First + 15)); Pos := Date'First + 16; end if; if Date'Length > 18 then if Date (Date'First + 16) /= ':' then raise Constraint_Error with "invalid date"; end if; Result.Second := Second_Number'Value (Date (Date'First + 17 .. Date'First + 18)); Pos := Date'First + 19; end if; -- ISO8601 timezone: +hh:mm or -hh:mm -- if Date'Length > Pos + 4 then -- if Date (Pos) /= '+' and Date (Pos) /= '-' and Date (Pos + 2) /= ':' then -- raise Constraint_Error with "invalid date"; -- end if; -- end if; else raise Constraint_Error with "invalid date"; end if; return Time_Of (Result); end Value; -- ------------------------------ -- Return the ISO8601 date. -- ------------------------------ function Image (Date : in Ada.Calendar.Time) return String is D : Date_Record; begin Split (D, Date); return Image (D); end Image; function Image (Date : in Date_Record) return String is To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 10) := "0000-00-00"; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); return Result; end Image; function Image (Date : in Ada.Calendar.Time; Precision : in Precision_Type) return String is D : Date_Record; begin Split (D, Date); return Image (D, Precision); end Image; function Image (Date : in Date_Record; Precision : in Precision_Type) return String is use type Ada.Calendar.Time_Zones.Time_Offset; To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 29) := "0000-00-00T00:00:00.000-00:00"; N, Tz : Natural; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); if Precision = YEAR then return Result (1 .. 4); end if; Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); if Precision = MONTH then return Result (1 .. 7); end if; Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); if Precision = DAY then return Result (1 .. 10); end if; Result (12) := To_Char (Date.Hour / 10); Result (13) := To_Char (Date.Hour mod 10); if Precision = HOUR then return Result (1 .. 13); end if; Result (15) := To_Char (Date.Minute / 10); Result (16) := To_Char (Date.Minute mod 10); if Precision = MINUTE then return Result (1 .. 16); end if; Result (18) := To_Char (Date.Second / 10); Result (19) := To_Char (Date.Second mod 10); if Precision = SECOND then return Result (1 .. 19); end if; N := Natural (Date.Sub_Second * 1000.0); Result (21) := To_Char (N / 100); Result (22) := To_Char ((N mod 100) / 10); Result (23) := To_Char (N mod 10); if Date.Time_Zone < 0 then Tz := Natural (-Date.Time_Zone); else Result (24) := '+'; Tz := Natural (Date.Time_Zone); end if; Result (25) := To_Char (Tz / 600); Result (26) := To_Char ((Tz / 60) mod 10); Tz := Tz mod 60; Result (28) := To_Char (Tz / 10); Result (29) := To_Char (Tz mod 10); return Result; end Image; end Util.Dates.ISO8601;
Use the new Time_Of function
Use the new Time_Of function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0c4b2d8704e81f4acee9fc1dc9fd26d01e3b7899
src/util-commands.ads
src/util-commands.ads
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Util.Commands is -- The argument list interface that gives access to command arguments. type Argument_List is limited interface; -- Get the number of arguments available. function Get_Count (List : in Argument_List) return Natural is abstract; -- Get the argument at the given position. function Get_Argument (List : in Argument_List; Pos : in Positive) return String is abstract; -- Get the command name. function Get_Command_Name (List : in Argument_List) return String is abstract; type Default_Argument_List (Offset : Natural) is new Argument_List with null record; -- Get the number of arguments available. overriding function Get_Count (List : in Default_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String; -- Get the command name. function Get_Command_Name (List : in Default_Argument_List) return String; end Util.Commands;
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Util.Commands is -- The argument list interface that gives access to command arguments. type Argument_List is limited interface; -- Get the number of arguments available. function Get_Count (List : in Argument_List) return Natural is abstract; -- Get the argument at the given position. function Get_Argument (List : in Argument_List; Pos : in Positive) return String is abstract; -- Get the command name. function Get_Command_Name (List : in Argument_List) return String is abstract; type Default_Argument_List (Offset : Natural) is new Argument_List with null record; -- Get the number of arguments available. overriding function Get_Count (List : in Default_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String; -- Get the command name. function Get_Command_Name (List : in Default_Argument_List) return String; type String_Argument_List (Max_Length : Positive; Max_Args : Positive) is new Argument_List with private; -- Set the argument list to the given string and split the arguments. procedure Initialize (List : in out String_Argument_List; Line : in String); -- Get the number of arguments available. overriding function Get_Count (List : in String_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in String_Argument_List; Pos : in Positive) return String; -- Get the command name. overriding function Get_Command_Name (List : in String_Argument_List) return String; private type Argument_Pos is array (Natural range <>) of Natural; type String_Argument_List (Max_Length : Positive; Max_Args : Positive) is new Argument_List with record Count : Natural := 0; Length : Natural := 0; Line : String (1 .. Max_Length); Start_Pos : Argument_Pos (0 .. Max_Args); End_Pos : Argument_Pos (0 .. Max_Args); end record; end Util.Commands;
Declare the String_Argument_List type with its operation to split a string into arguments and provide the Argument_List interface operations
Declare the String_Argument_List type with its operation to split a string into arguments and provide the Argument_List interface operations
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f37ae047e9f3f9178527449608af8e332d0aa182
src/core/util-refs.adb
src/core/util-refs.adb
----------------------------------------------------------------------- -- util-refs -- Reference Counting -- Copyright (C) 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 Ada.Unchecked_Deallocation; package body Util.Refs is package body Indefinite_References is -- ------------------------------ -- Create an element and return a reference to that element. -- ------------------------------ function Create (Value : in Element_Access) return Ref is begin return Result : Ref do Result.Target := Value; Util.Concurrent.Counters.Increment (Result.Target.Ref_Counter); end return; end Create; -- ------------------------------ -- Get the element access value. -- ------------------------------ function Value (Object : in Ref'Class) return Element_Accessor is begin return Element_Accessor '(Element => Object.Target); end Value; -- ------------------------------ -- Returns true if the reference does not contain any element. -- ------------------------------ function Is_Null (Object : in Ref'Class) return Boolean is begin return Object.Target = null; end Is_Null; function "=" (Left, Right : in Ref'Class) return Boolean is begin return Left.Target = Right.Target; end "="; package body Atomic is protected body Atomic_Ref is -- ------------------------------ -- Get the reference -- ------------------------------ function Get return Ref is begin return Value; end Get; -- ------------------------------ -- Change the reference -- ------------------------------ procedure Set (Object : in Ref) is begin Value := Object; end Set; end Atomic_Ref; end Atomic; procedure Free is new Ada.Unchecked_Deallocation (Object => Element_Type, Name => Element_Access); -- ------------------------------ -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Ref) is Release : Boolean; begin if Obj.Target /= null then Util.Concurrent.Counters.Decrement (Obj.Target.Ref_Counter, Release); if Release then Obj.Target.Finalize; Free (Obj.Target); else Obj.Target := null; end if; end if; end Finalize; -- ------------------------------ -- Update the reference counter after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Ref) is begin if Obj.Target /= null then Util.Concurrent.Counters.Increment (Obj.Target.Ref_Counter); end if; end Adjust; end Indefinite_References; package body References is -- ------------------------------ -- Create an element and return a reference to that element. -- ------------------------------ function Create return Ref is begin return IR.Create (new Element_Type); end Create; end References; package body General_References is -- ------------------------------ -- Create an element and return a reference to that element. -- ------------------------------ function Create return Ref is begin return Result : Ref do Result.Target := new Ref_Data; Util.Concurrent.Counters.Increment (Result.Target.Ref_Counter); end return; end Create; -- ------------------------------ -- Get the element access value. -- ------------------------------ function Value (Object : in Ref'Class) return Element_Accessor is begin return Element_Accessor '(Element => Object.Target.Data'Access); end Value; -- ------------------------------ -- Returns true if the reference does not contain any element. -- ------------------------------ function Is_Null (Object : in Ref'Class) return Boolean is begin return Object.Target = null; end Is_Null; function "=" (Left, Right : in Ref'Class) return Boolean is begin return Left.Target = Right.Target; end "="; package body Atomic is protected body Atomic_Ref is -- ------------------------------ -- Get the reference -- ------------------------------ function Get return Ref is begin return Value; end Get; -- ------------------------------ -- Change the reference -- ------------------------------ procedure Set (Object : in Ref) is begin Value := Object; end Set; end Atomic_Ref; end Atomic; procedure Free is new Ada.Unchecked_Deallocation (Object => Ref_Data, Name => Ref_Data_Access); -- ------------------------------ -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Ref) is Release : Boolean; begin if Obj.Target /= null then Util.Concurrent.Counters.Decrement (Obj.Target.Ref_Counter, Release); if Release then Finalize (Obj.Target.Data); Free (Obj.Target); else Obj.Target := null; end if; end if; end Finalize; -- ------------------------------ -- Update the reference counter after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Ref) is begin if Obj.Target /= null then Util.Concurrent.Counters.Increment (Obj.Target.Ref_Counter); end if; end Adjust; end General_References; end Util.Refs;
----------------------------------------------------------------------- -- util-refs -- Reference Counting -- Copyright (C) 2010, 2011, 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.Unchecked_Deallocation; package body Util.Refs is package body Indefinite_References is -- ------------------------------ -- Create an element and return a reference to that element. -- ------------------------------ function Create (Value : in Element_Access) return Ref is begin return Result : Ref do Result.Target := Value; Util.Concurrent.Counters.Increment (Result.Target.Ref_Counter); end return; end Create; -- ------------------------------ -- Get the element access value. -- ------------------------------ function Value (Object : in Ref'Class) return Element_Accessor is begin return Element_Accessor '(Element => Object.Target); end Value; -- ------------------------------ -- Returns true if the reference does not contain any element. -- ------------------------------ function Is_Null (Object : in Ref'Class) return Boolean is begin return Object.Target = null; end Is_Null; function "=" (Left, Right : in Ref'Class) return Boolean is begin return Left.Target = Right.Target; end "="; package body Atomic is protected body Atomic_Ref is -- ------------------------------ -- Get the reference -- ------------------------------ function Get return Ref is begin return Value; end Get; -- ------------------------------ -- Change the reference -- ------------------------------ procedure Set (Object : in Ref) is begin Value := Object; end Set; end Atomic_Ref; end Atomic; procedure Free is new Ada.Unchecked_Deallocation (Object => Element_Type, Name => Element_Access); -- ------------------------------ -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Ref) is Release : Boolean; begin if Obj.Target /= null then Util.Concurrent.Counters.Decrement (Obj.Target.Ref_Counter, Release); if Release then Obj.Target.Finalize; Free (Obj.Target); else Obj.Target := null; end if; end if; end Finalize; -- ------------------------------ -- Update the reference counter after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Ref) is begin if Obj.Target /= null then Util.Concurrent.Counters.Increment (Obj.Target.Ref_Counter); end if; end Adjust; end Indefinite_References; package body References is -- ------------------------------ -- Create an element and return a reference to that element. -- ------------------------------ function Create return Ref is begin return IR.Create (new Element_Type); end Create; end References; package body General_References is -- ------------------------------ -- Create an element and return a reference to that element. -- ------------------------------ function Create return Ref is begin return Result : Ref do Result.Target := new Ref_Data; Util.Concurrent.Counters.Increment (Result.Target.Ref_Counter); end return; end Create; -- ------------------------------ -- Get the element access value. -- ------------------------------ function Value (Object : in Ref'Class) return Element_Accessor is begin -- GCC 10 requires the Unrestricted_Access while GCC < 10 allowed Access... -- It is safe because the Ref handles the copy and Element_Accessor is limited. return Element_Accessor '(Element => Object.Target.Data'Unrestricted_Access); end Value; -- ------------------------------ -- Returns true if the reference does not contain any element. -- ------------------------------ function Is_Null (Object : in Ref'Class) return Boolean is begin return Object.Target = null; end Is_Null; function "=" (Left, Right : in Ref'Class) return Boolean is begin return Left.Target = Right.Target; end "="; package body Atomic is protected body Atomic_Ref is -- ------------------------------ -- Get the reference -- ------------------------------ function Get return Ref is begin return Value; end Get; -- ------------------------------ -- Change the reference -- ------------------------------ procedure Set (Object : in Ref) is begin Value := Object; end Set; end Atomic_Ref; end Atomic; procedure Free is new Ada.Unchecked_Deallocation (Object => Ref_Data, Name => Ref_Data_Access); -- ------------------------------ -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Ref) is Release : Boolean; begin if Obj.Target /= null then Util.Concurrent.Counters.Decrement (Obj.Target.Ref_Counter, Release); if Release then Finalize (Obj.Target.Data); Free (Obj.Target); else Obj.Target := null; end if; end if; end Finalize; -- ------------------------------ -- Update the reference counter after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Ref) is begin if Obj.Target /= null then Util.Concurrent.Counters.Increment (Obj.Target.Ref_Counter); end if; end Adjust; end General_References; end Util.Refs;
Fix compilation with GNAT 10
Fix compilation with GNAT 10
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8c5a7720d9f5aedc9567fa7a8abdf1d6853fbfde
src/orka/implementation/glfw/orka-windows-glfw.adb
src/orka/implementation/glfw/orka-windows-glfw.adb
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Glfw.Errors; with Glfw.Windows.Context; with Glfw.Windows.Hints; with Orka.Inputs.GLFW; with Orka.Logging; package body Orka.Windows.GLFW is use Orka.Logging; package Messages is new Orka.Logging.Messages (Other); procedure Print_Error (Code : Standard.Glfw.Errors.Kind; Description : String) is begin Messages.Insert (Error, "GLFW " & Code'Image & ": " & Trim (Description)); end Print_Error; function Initialize (Major, Minor : Natural; Debug : Boolean := False) return Active_GLFW'Class is begin -- Initialize GLFW Standard.Glfw.Errors.Set_Callback (Print_Error'Access); Standard.Glfw.Init; -- Initialize OpenGL context Standard.Glfw.Windows.Hints.Set_Minimum_OpenGL_Version (Major, Minor); Standard.Glfw.Windows.Hints.Set_Forward_Compat (True); Standard.Glfw.Windows.Hints.Set_Profile (Standard.Glfw.Windows.Context.Core_Profile); Standard.Glfw.Windows.Hints.Set_Debug_Context (Debug); return Active_GLFW'(Ada.Finalization.Limited_Controlled with Debug => Debug, Finalized => False); end Initialize; overriding procedure Finalize (Object : in out Active_GLFW) is begin if not Object.Finalized then if Object.Debug then Messages.Insert (Debug, "Shutting down GLFW"); end if; Standard.Glfw.Shutdown; Object.Finalized := True; end if; end Finalize; overriding procedure Finalize (Object : in out GLFW_Window) is begin if not Object.Finalized then Object.Destroy; Object.Finalized := True; end if; end Finalize; function Create_Window (Width, Height : Positive; Samples : Natural := 0; Visible, Resizable : Boolean := True) return Window'Class is package Windows renames Standard.Glfw.Windows; begin return Result : GLFW_Window := GLFW_Window'(Windows.Window with Input => Inputs.GLFW.Create_Pointer_Input, Finalized => False, others => <>) do declare Reference : constant Windows.Window_Reference := Windows.Window (Window'Class (Result))'Access; begin Windows.Hints.Set_Visible (Visible); Windows.Hints.Set_Resizable (Resizable); Windows.Hints.Set_Samples (Samples); Reference.Init (Standard.Glfw.Size (Width), Standard.Glfw.Size (Height), ""); Inputs.GLFW.GLFW_Pointer_Input (Result.Input.all).Set_Window (Reference); declare Width, Height : Standard.Glfw.Size; begin Reference.Get_Framebuffer_Size (Width, Height); Result.Framebuffer_Size_Changed (Natural (Width), Natural (Height)); end; -- Callbacks Reference.Enable_Callback (Windows.Callbacks.Close); Reference.Enable_Callback (Windows.Callbacks.Mouse_Button); Reference.Enable_Callback (Windows.Callbacks.Mouse_Position); Reference.Enable_Callback (Windows.Callbacks.Mouse_Scroll); Reference.Enable_Callback (Windows.Callbacks.Key); Reference.Enable_Callback (Windows.Callbacks.Framebuffer_Size); Windows.Context.Make_Current (Reference); end; end return; end Create_Window; overriding function Pointer_Input (Object : GLFW_Window) return Inputs.Pointer_Input_Ptr is (Object.Input); overriding function Width (Object : GLFW_Window) return Positive is (Object.Width); overriding function Height (Object : GLFW_Window) return Positive is (Object.Height); overriding procedure Set_Title (Object : in out GLFW_Window; Value : String) is begin Standard.Glfw.Windows.Window (Object)'Access.Set_Title (Value); end Set_Title; overriding procedure Close (Object : in out GLFW_Window) is begin Object.Set_Should_Close (True); end Close; overriding function Should_Close (Object : in out GLFW_Window) return Boolean is begin return Standard.Glfw.Windows.Window (Object)'Access.Should_Close; end Should_Close; overriding procedure Process_Input (Object : in out GLFW_Window) is begin Standard.Glfw.Input.Poll_Events; -- Update position of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Position (Object.Position_X, Object.Position_Y); -- Update scroll offset of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Scroll_Offset (Object.Scroll_X, Object.Scroll_Y); end Process_Input; overriding procedure Swap_Buffers (Object : in out GLFW_Window) is begin Standard.Glfw.Windows.Context.Swap_Buffers (Object'Access); end Swap_Buffers; overriding procedure Close_Requested (Object : not null access GLFW_Window) is begin -- TODO Call Object.Set_Should_Close (False); if certain conditions are not met null; end Close_Requested; overriding procedure Key_Changed (Object : not null access GLFW_Window; Key : Standard.Glfw.Input.Keys.Key; Scancode : Standard.Glfw.Input.Keys.Scancode; Action : Standard.Glfw.Input.Keys.Action; Mods : Standard.Glfw.Input.Keys.Modifiers) is use Standard.Glfw.Input.Keys; begin if Key = Escape and Action = Press then Object.Set_Should_Close (True); end if; -- TODO Add Button_Input object end Key_Changed; overriding procedure Mouse_Position_Changed (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Coordinate) is begin Object.Position_X := GL.Types.Double (X); Object.Position_Y := GL.Types.Double (Y); end Mouse_Position_Changed; overriding procedure Mouse_Scrolled (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Scroll_Offset) is use type GL.Types.Double; begin Object.Scroll_X := Object.Scroll_X + GL.Types.Double (X); Object.Scroll_Y := Object.Scroll_Y + GL.Types.Double (Y); end Mouse_Scrolled; overriding procedure Mouse_Button_Changed (Object : not null access GLFW_Window; Button : Standard.Glfw.Input.Mouse.Button; State : Standard.Glfw.Input.Button_State; Mods : Standard.Glfw.Input.Keys.Modifiers) is begin Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Button_State (Button, State); end Mouse_Button_Changed; overriding procedure Framebuffer_Size_Changed (Object : not null access GLFW_Window; Width, Height : Natural) is begin Object.Width := Width; Object.Height := Height; end Framebuffer_Size_Changed; end Orka.Windows.GLFW;
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Glfw.Errors; with Glfw.Windows.Context; with Glfw.Windows.Hints; with Orka.Inputs.GLFW; with Orka.Logging; package body Orka.Windows.GLFW is use Orka.Logging; package Messages is new Orka.Logging.Messages (Other); procedure Print_Error (Code : Standard.Glfw.Errors.Kind; Description : String) is begin Messages.Insert (Error, "GLFW " & Code'Image & ": " & Trim (Description)); end Print_Error; function Initialize (Major, Minor : Natural; Debug : Boolean := False) return Active_GLFW'Class is begin -- Initialize GLFW Standard.Glfw.Errors.Set_Callback (Print_Error'Access); Standard.Glfw.Init; -- Initialize OpenGL context Standard.Glfw.Windows.Hints.Set_Minimum_OpenGL_Version (Major, Minor); Standard.Glfw.Windows.Hints.Set_Forward_Compat (True); Standard.Glfw.Windows.Hints.Set_Client_API (Standard.Glfw.Windows.Context.OpenGL); Standard.Glfw.Windows.Hints.Set_Profile (Standard.Glfw.Windows.Context.Core_Profile); Standard.Glfw.Windows.Hints.Set_Debug_Context (Debug); return Active_GLFW'(Ada.Finalization.Limited_Controlled with Debug => Debug, Finalized => False); end Initialize; overriding procedure Finalize (Object : in out Active_GLFW) is begin if not Object.Finalized then if Object.Debug then Messages.Insert (Debug, "Shutting down GLFW"); end if; Standard.Glfw.Shutdown; Object.Finalized := True; end if; end Finalize; overriding procedure Finalize (Object : in out GLFW_Window) is begin if not Object.Finalized then Object.Destroy; Object.Finalized := True; end if; end Finalize; function Create_Window (Width, Height : Positive; Samples : Natural := 0; Visible, Resizable : Boolean := True) return Window'Class is package Windows renames Standard.Glfw.Windows; begin return Result : GLFW_Window := GLFW_Window'(Windows.Window with Input => Inputs.GLFW.Create_Pointer_Input, Finalized => False, others => <>) do declare Reference : constant Windows.Window_Reference := Windows.Window (Window'Class (Result))'Access; begin Windows.Hints.Set_Visible (Visible); Windows.Hints.Set_Resizable (Resizable); Windows.Hints.Set_Samples (Samples); Reference.Init (Standard.Glfw.Size (Width), Standard.Glfw.Size (Height), ""); Inputs.GLFW.GLFW_Pointer_Input (Result.Input.all).Set_Window (Reference); declare Width, Height : Standard.Glfw.Size; begin Reference.Get_Framebuffer_Size (Width, Height); Result.Framebuffer_Size_Changed (Natural (Width), Natural (Height)); end; -- Callbacks Reference.Enable_Callback (Windows.Callbacks.Close); Reference.Enable_Callback (Windows.Callbacks.Mouse_Button); Reference.Enable_Callback (Windows.Callbacks.Mouse_Position); Reference.Enable_Callback (Windows.Callbacks.Mouse_Scroll); Reference.Enable_Callback (Windows.Callbacks.Key); Reference.Enable_Callback (Windows.Callbacks.Framebuffer_Size); Windows.Context.Make_Current (Reference); end; end return; end Create_Window; overriding function Pointer_Input (Object : GLFW_Window) return Inputs.Pointer_Input_Ptr is (Object.Input); overriding function Width (Object : GLFW_Window) return Positive is (Object.Width); overriding function Height (Object : GLFW_Window) return Positive is (Object.Height); overriding procedure Set_Title (Object : in out GLFW_Window; Value : String) is begin Standard.Glfw.Windows.Window (Object)'Access.Set_Title (Value); end Set_Title; overriding procedure Close (Object : in out GLFW_Window) is begin Object.Set_Should_Close (True); end Close; overriding function Should_Close (Object : in out GLFW_Window) return Boolean is begin return Standard.Glfw.Windows.Window (Object)'Access.Should_Close; end Should_Close; overriding procedure Process_Input (Object : in out GLFW_Window) is begin Standard.Glfw.Input.Poll_Events; -- Update position of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Position (Object.Position_X, Object.Position_Y); -- Update scroll offset of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Scroll_Offset (Object.Scroll_X, Object.Scroll_Y); end Process_Input; overriding procedure Swap_Buffers (Object : in out GLFW_Window) is begin Standard.Glfw.Windows.Context.Swap_Buffers (Object'Access); end Swap_Buffers; overriding procedure Close_Requested (Object : not null access GLFW_Window) is begin -- TODO Call Object.Set_Should_Close (False); if certain conditions are not met null; end Close_Requested; overriding procedure Key_Changed (Object : not null access GLFW_Window; Key : Standard.Glfw.Input.Keys.Key; Scancode : Standard.Glfw.Input.Keys.Scancode; Action : Standard.Glfw.Input.Keys.Action; Mods : Standard.Glfw.Input.Keys.Modifiers) is use Standard.Glfw.Input.Keys; begin if Key = Escape and Action = Press then Object.Set_Should_Close (True); end if; -- TODO Add Button_Input object end Key_Changed; overriding procedure Mouse_Position_Changed (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Coordinate) is begin Object.Position_X := GL.Types.Double (X); Object.Position_Y := GL.Types.Double (Y); end Mouse_Position_Changed; overriding procedure Mouse_Scrolled (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Scroll_Offset) is use type GL.Types.Double; begin Object.Scroll_X := Object.Scroll_X + GL.Types.Double (X); Object.Scroll_Y := Object.Scroll_Y + GL.Types.Double (Y); end Mouse_Scrolled; overriding procedure Mouse_Button_Changed (Object : not null access GLFW_Window; Button : Standard.Glfw.Input.Mouse.Button; State : Standard.Glfw.Input.Button_State; Mods : Standard.Glfw.Input.Keys.Modifiers) is begin Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Button_State (Button, State); end Mouse_Button_Changed; overriding procedure Framebuffer_Size_Changed (Object : not null access GLFW_Window; Width, Height : Natural) is begin Object.Width := Width; Object.Height := Height; end Framebuffer_Size_Changed; end Orka.Windows.GLFW;
Make sure to request an OpenGL, not OpenGL ES, context
orka: Make sure to request an OpenGL, not OpenGL ES, context Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
db99ac88b4374eb3f8aa0c69c2e61c093b2ffb64
tests/natools-s_expressions-atom_buffers-tests.adb
tests/natools-s_expressions-atom_buffers-tests.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Test_Tools; package body Natools.S_Expressions.Atom_Buffers.Tests is ---------------------- -- Whole Test Suite -- ---------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Test_Block_Append (Report); Test_Octet_Append (Report); Test_Preallocate (Report); Test_Query (Report); Test_Query_Null (Report); Test_Reset (Report); Test_Reverse_Append (Report); Test_Invert (Report); Test_Empty_Append (Report); end All_Tests; ---------------------- -- Individual Tests -- ---------------------- procedure Test_Block_Append (Report : in out NT.Reporter'Class) is Name : constant String := "Append in blocks"; Data : Atom (0 .. 255); begin for O in Octet loop Data (Count (O)) := O; end loop; declare Buffer : Atom_Buffer; begin Buffer.Append (Data (0 .. 10)); Buffer.Append (Data (11 .. 11)); Buffer.Append (Data (12 .. 101)); Buffer.Append (Data (102 .. 101)); Buffer.Append (Data (102 .. 255)); Test_Tools.Test_Atom (Report, Name, Data, Buffer.Data); end; exception when Error : others => Report.Report_Exception (Name, Error); end Test_Block_Append; procedure Test_Invert (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Invert procedure"); Source : Atom (1 .. 10); Inverse : Atom (1 .. 10); begin for I in Source'Range loop Source (I) := 10 + Octet (I); Inverse (11 - I) := Source (I); end loop; declare Buffer : Atom_Buffer; begin Buffer.Invert; Test_Tools.Test_Atom (Test, Null_Atom, Buffer.Data); Buffer.Append (Source (1 .. 1)); Buffer.Invert; Test_Tools.Test_Atom (Test, Source (1 .. 1), Buffer.Data); Buffer.Append (Source (2 .. 7)); Buffer.Invert; Test_Tools.Test_Atom (Test, Inverse (4 .. 10), Buffer.Data); Buffer.Invert; Buffer.Append (Source (8 .. 10)); Buffer.Invert; Test_Tools.Test_Atom (Test, Inverse, Buffer.Data); end; exception when Error : others => Test.Report_Exception (Error); end Test_Invert; procedure Test_Octet_Append (Report : in out NT.Reporter'Class) is Name : constant String := "Append octet by octet"; Data : Atom (0 .. 255); begin for O in Octet loop Data (Count (O)) := O; end loop; declare Buffer : Atom_Buffer; begin for O in Octet loop Buffer.Append (O); end loop; Test_Tools.Test_Atom (Report, Name, Data, Buffer.Data); end; exception when Error : others => Report.Report_Exception (Name, Error); end Test_Octet_Append; procedure Test_Preallocate (Report : in out NT.Reporter'Class) is Name : constant String := "Preallocation of memory"; begin declare Buffer : Atom_Buffer; begin Buffer.Preallocate (256); declare Old_Accessor : Atom_Refs.Accessor := Buffer.Raw_Query; begin for O in Octet loop Buffer.Append (O); end loop; Report.Item (Name, NT.To_Result (Old_Accessor.Data = Buffer.Raw_Query.Data)); end; end; exception when Error : others => Report.Report_Exception (Name, Error); end Test_Preallocate; procedure Test_Query (Report : in out NT.Reporter'Class) is Name : constant String := "Accessors"; Data : Atom (0 .. 255); begin for O in Octet loop Data (Count (O)) := O; end loop; declare Buffer : Atom_Buffer; begin Buffer.Append (Data); if Buffer.Length /= Data'Length then Report.Item (Name, NT.Fail); Report.Info ("Buffer.Length returned" & Count'Image (Buffer.Length) & ", expected" & Count'Image (Data'Length)); return; end if; if Buffer.Data /= Data then Report.Item (Name, NT.Fail); Report.Info ("Data, returning an Atom"); Test_Tools.Dump_Atom (Report, Buffer.Data, "Found"); Test_Tools.Dump_Atom (Report, Data, "Expected"); return; end if; if Buffer.Raw_Query.Data.all /= Data then Report.Item (Name, NT.Fail); Report.Info ("Raw_Query, returning an accessor"); Test_Tools.Dump_Atom (Report, Buffer.Raw_Query.Data.all, "Found"); Test_Tools.Dump_Atom (Report, Data, "Expected"); return; end if; if Buffer.Element (25) /= Data (24) then Report.Item (Name, NT.Fail); Report.Info ("Element, returning an octet"); return; end if; declare O, P : Octet; begin Buffer.Pop (O); Buffer.Pop (P); if O /= Data (Data'Last) or P /= Data (Data'Last - 1) or Buffer.Data /= Data (Data'First .. Data'Last - 2) then Report.Item (Name, NT.Fail); Report.Info ("Pop of an octet: " & Octet'Image (P) & " " & Octet'Image (O)); Test_Tools.Dump_Atom (Report, Buffer.Data, "Remaining"); Test_Tools.Dump_Atom (Report, Data, "Expected"); return; end if; Buffer.Append ((P, O)); if Buffer.Data /= Data then Report.Item (Name, NT.Fail); Report.Info ("Append back after Pop"); Test_Tools.Dump_Atom (Report, Buffer.Data, "Found"); Test_Tools.Dump_Atom (Report, Data, "Expected"); return; end if; end; declare Retrieved : Atom (10 .. 310); Length : Count; begin Buffer.Read (Retrieved, Length); if Length /= Data'Length or else Retrieved (10 .. Length + 9) /= Data then Report.Item (Name, NT.Fail); Report.Info ("Read into an existing buffer"); Report.Info ("Length returned" & Count'Image (Length) & ", expected" & Count'Image (Data'Length)); Test_Tools.Dump_Atom (Report, Retrieved (10 .. Length + 9), "Found"); Test_Tools.Dump_Atom (Report, Data, "Expected"); return; end if; end; declare Retrieved : Atom (20 .. 50); Length : Count; begin Buffer.Read (Retrieved, Length); if Length /= Data'Length or else Retrieved /= Data (0 .. 30) then Report.Item (Name, NT.Fail); Report.Info ("Read into a buffer too small"); Report.Info ("Length returned" & Count'Image (Length) & ", expected" & Count'Image (Data'Length)); Test_Tools.Dump_Atom (Report, Retrieved, "Found"); Test_Tools.Dump_Atom (Report, Data (0 .. 30), "Expected"); return; end if; end; declare procedure Check (Found : in Atom); Result : Boolean := False; procedure Check (Found : in Atom) is begin Result := Found = Data; end Check; begin Buffer.Query (Check'Access); if not Result then Report.Item (Name, NT.Fail); Report.Info ("Query with callback"); return; end if; end; end; Report.Item (Name, NT.Success); exception when Error : others => Report.Report_Exception (Name, Error); end Test_Query; procedure Test_Query_Null (Report : in out NT.Reporter'Class) is Name : constant String := "Accessor variants against a null buffer"; begin declare Buffer : Atom_Buffer; begin if Buffer.Data /= Null_Atom then Report.Item (Name, NT.Fail); Report.Info ("Data, returning an Atom"); Test_Tools.Dump_Atom (Report, Buffer.Data, "Found"); return; end if; if Buffer.Raw_Query.Data.all /= Null_Atom then Report.Item (Name, NT.Fail); Report.Info ("Raw_Query, returning an accessor"); Test_Tools.Dump_Atom (Report, Buffer.Raw_Query.Data.all, "Found"); return; end if; declare Retrieved : Atom (1 .. 10); Length : Count; begin Buffer.Read (Retrieved, Length); if Length /= 0 then Report.Item (Name, NT.Fail); Report.Info ("Read into an existing buffer"); Report.Info ("Length returned" & Count'Image (Length) & ", expected 0"); return; end if; end; declare procedure Check (Found : in Atom); Result : Boolean := False; procedure Check (Found : in Atom) is begin Result := Found = Null_Atom; end Check; begin Buffer.Query (Check'Access); if not Result then Report.Item (Name, NT.Fail); Report.Info ("Query with callback"); return; end if; end; end; Report.Item (Name, NT.Success); exception when Error : others => Report.Report_Exception (Name, Error); end Test_Query_Null; procedure Test_Reset (Report : in out NT.Reporter'Class) is Name : constant String := "Reset procedures"; begin declare Buffer : Atom_Buffer; begin for O in Octet loop Buffer.Append (O); end loop; declare Accessor : Atom_Refs.Accessor := Buffer.Raw_Query; begin Buffer.Soft_Reset; if Buffer.Length /= 0 then Report.Item (Name, NT.Fail); Report.Info ("Soft reset left length" & Count'Image (Buffer.Length)); return; end if; if Buffer.Raw_Query.Data /= Accessor.Data then Report.Item (Name, NT.Fail); Report.Info ("Soft reset changed storage area"); return; end if; if Buffer.Raw_Query.Data.all'Length /= Buffer.Available then Report.Item (Name, NT.Fail); Report.Info ("Available length inconsistency, recorded" & Count'Image (Buffer.Available) & ", actual" & Count'Image (Buffer.Raw_Query.Data.all'Length)); return; end if; if Buffer.Data'Length /= Buffer.Used then Report.Item (Name, NT.Fail); Report.Info ("Used length inconsistency, recorded" & Count'Image (Buffer.Used) & ", actual" & Count'Image (Buffer.Data'Length)); return; end if; end; for O in Octet'(10) .. Octet'(50) loop Buffer.Append (O); end loop; Buffer.Hard_Reset; if Buffer.Length /= 0 or else Buffer.Available /= 0 or else not Buffer.Ref.Is_Empty then Report.Item (Name, NT.Fail); Report.Info ("Hard reset did not completely clean structure"); end if; end; Report.Item (Name, NT.Success); exception when Error : others => Report.Report_Exception (Name, Error); end Test_Reset; procedure Test_Reverse_Append (Report : in out NT.Reporter'Class) is Name : constant String := "procedure Append_Reverse"; Source_1 : Atom (1 .. 10); Source_2 : Atom (1 .. 1); Source_3 : Atom (51 .. 65); Source_4 : Atom (1 .. 0); Source_5 : Atom (101 .. 114); Expected : Atom (1 .. 40); begin for I in Source_1'Range loop Source_1 (I) := 10 + Octet (I); Expected (Expected'First + Source_1'Last - I) := Source_1 (I); end loop; for I in Source_2'Range loop Source_2 (I) := 42; Expected (Expected'First + Source_1'Length + Source_2'Last - I) := Source_2 (I); end loop; for I in Source_3'Range loop Source_3 (I) := Octet (I); Expected (Expected'First + Source_1'Length + Source_2'Length + I - Source_3'First) := Source_3 (I); end loop; for I in Source_5'Range loop Source_5 (I) := Octet (I); Expected (Expected'First + Source_1'Length + Source_2'Length + Source_3'Length + Source_5'Last - I) := Source_5 (I); end loop; declare Buffer : Atom_Buffer; begin Buffer.Append_Reverse (Source_1); Buffer.Append_Reverse (Source_2); Buffer.Append (Source_3); Buffer.Append_Reverse (Source_4); Buffer.Append_Reverse (Source_5); Test_Tools.Test_Atom (Report, Name, Expected, Buffer.Data); end; exception when Error : others => Report.Report_Exception (Name, Error); end Test_Reverse_Append; procedure Test_Empty_Append (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Empty append on empty buffer"); begin declare Buffer : Atom_Buffer; begin Buffer.Append (Null_Atom); Test_Tools.Test_Atom (Test, Null_Atom, Buffer.Data); end; exception when Error : others => Test.Report_Exception (Error); end Test_Empty_Append; end Natools.S_Expressions.Atom_Buffers.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 Natools.S_Expressions.Test_Tools; package body Natools.S_Expressions.Atom_Buffers.Tests is ---------------------- -- Whole Test Suite -- ---------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Test_Block_Append (Report); Test_Octet_Append (Report); Test_Preallocate (Report); Test_Query (Report); Test_Query_Null (Report); Test_Reset (Report); Test_Reverse_Append (Report); Test_Invert (Report); Test_Empty_Append (Report); end All_Tests; ---------------------- -- Individual Tests -- ---------------------- procedure Test_Block_Append (Report : in out NT.Reporter'Class) is Name : constant String := "Append in blocks"; Data : Atom (0 .. 255); begin for O in Octet loop Data (Count (O)) := O; end loop; declare Buffer : Atom_Buffer; begin Buffer.Append (Data (0 .. 10)); Buffer.Append (Data (11 .. 11)); Buffer.Append (Data (12 .. 101)); Buffer.Append (Data (102 .. 101)); Buffer.Append (Data (102 .. 255)); Test_Tools.Test_Atom (Report, Name, Data, Buffer.Data); end; exception when Error : others => Report.Report_Exception (Name, Error); end Test_Block_Append; procedure Test_Invert (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Invert procedure"); Source : Atom (1 .. 10); Inverse : Atom (1 .. 10); begin for I in Source'Range loop Source (I) := 10 + Octet (I); Inverse (11 - I) := Source (I); end loop; declare Buffer : Atom_Buffer; begin Buffer.Invert; Test_Tools.Test_Atom (Test, Null_Atom, Buffer.Data); Buffer.Append (Source (1 .. 1)); Buffer.Invert; Test_Tools.Test_Atom (Test, Source (1 .. 1), Buffer.Data); Buffer.Append (Source (2 .. 7)); Buffer.Invert; Test_Tools.Test_Atom (Test, Inverse (4 .. 10), Buffer.Data); Buffer.Invert; Buffer.Append (Source (8 .. 10)); Buffer.Invert; Test_Tools.Test_Atom (Test, Inverse, Buffer.Data); end; exception when Error : others => Test.Report_Exception (Error); end Test_Invert; procedure Test_Octet_Append (Report : in out NT.Reporter'Class) is Name : constant String := "Append octet by octet"; Data : Atom (0 .. 255); begin for O in Octet loop Data (Count (O)) := O; end loop; declare Buffer : Atom_Buffer; begin for O in Octet loop Buffer.Append (O); end loop; Test_Tools.Test_Atom (Report, Name, Data, Buffer.Data); end; exception when Error : others => Report.Report_Exception (Name, Error); end Test_Octet_Append; procedure Test_Preallocate (Report : in out NT.Reporter'Class) is Name : constant String := "Preallocation of memory"; begin declare Buffer : Atom_Buffer; begin Buffer.Preallocate (256); declare Old_Accessor : Atom_Refs.Accessor := Buffer.Raw_Query; begin for O in Octet loop Buffer.Append (O); end loop; Report.Item (Name, NT.To_Result (Old_Accessor.Data = Buffer.Raw_Query.Data)); end; end; exception when Error : others => Report.Report_Exception (Name, Error); end Test_Preallocate; procedure Test_Query (Report : in out NT.Reporter'Class) is Name : constant String := "Accessors"; Data : Atom (0 .. 255); begin for O in Octet loop Data (Count (O)) := O; end loop; declare Buffer : Atom_Buffer; begin Buffer.Append (Data); if Buffer.Length /= Data'Length then Report.Item (Name, NT.Fail); Report.Info ("Buffer.Length returned" & Count'Image (Buffer.Length) & ", expected" & Count'Image (Data'Length)); return; end if; if Buffer.Data /= Data then Report.Item (Name, NT.Fail); Report.Info ("Data, returning an Atom"); Test_Tools.Dump_Atom (Report, Buffer.Data, "Found"); Test_Tools.Dump_Atom (Report, Data, "Expected"); return; end if; if Buffer.Raw_Query.Data.all /= Data then Report.Item (Name, NT.Fail); Report.Info ("Raw_Query, returning an accessor"); Test_Tools.Dump_Atom (Report, Buffer.Raw_Query.Data.all, "Found"); Test_Tools.Dump_Atom (Report, Data, "Expected"); return; end if; if Buffer.Element (25) /= Data (24) then Report.Item (Name, NT.Fail); Report.Info ("Element, returning an octet"); return; end if; declare O, P : Octet; begin Buffer.Pop (O); Buffer.Pop (P); if O /= Data (Data'Last) or P /= Data (Data'Last - 1) or Buffer.Data /= Data (Data'First .. Data'Last - 2) then Report.Item (Name, NT.Fail); Report.Info ("Pop of an octet: " & Octet'Image (P) & " " & Octet'Image (O)); Test_Tools.Dump_Atom (Report, Buffer.Data, "Remaining"); Test_Tools.Dump_Atom (Report, Data, "Expected"); return; end if; Buffer.Append ((P, O)); if Buffer.Data /= Data then Report.Item (Name, NT.Fail); Report.Info ("Append back after Pop"); Test_Tools.Dump_Atom (Report, Buffer.Data, "Found"); Test_Tools.Dump_Atom (Report, Data, "Expected"); return; end if; end; declare Retrieved : Atom (10 .. 310); Length : Count; begin Buffer.Read (Retrieved, Length); if Length /= Data'Length or else Retrieved (10 .. Length + 9) /= Data then Report.Item (Name, NT.Fail); Report.Info ("Read into an existing buffer"); Report.Info ("Length returned" & Count'Image (Length) & ", expected" & Count'Image (Data'Length)); Test_Tools.Dump_Atom (Report, Retrieved (10 .. Length + 9), "Found"); Test_Tools.Dump_Atom (Report, Data, "Expected"); return; end if; end; declare Retrieved : Atom (20 .. 50); Length : Count; begin Buffer.Read (Retrieved, Length); if Length /= Data'Length or else Retrieved /= Data (0 .. 30) then Report.Item (Name, NT.Fail); Report.Info ("Read into a buffer too small"); Report.Info ("Length returned" & Count'Image (Length) & ", expected" & Count'Image (Data'Length)); Test_Tools.Dump_Atom (Report, Retrieved, "Found"); Test_Tools.Dump_Atom (Report, Data (0 .. 30), "Expected"); return; end if; end; declare procedure Check (Found : in Atom); Result : Boolean := False; procedure Check (Found : in Atom) is begin Result := Found = Data; end Check; begin Buffer.Query (Check'Access); if not Result then Report.Item (Name, NT.Fail); Report.Info ("Query with callback"); return; end if; end; end; Report.Item (Name, NT.Success); exception when Error : others => Report.Report_Exception (Name, Error); end Test_Query; procedure Test_Query_Null (Report : in out NT.Reporter'Class) is Name : constant String := "Accessor variants against a null buffer"; begin declare Buffer : Atom_Buffer; begin if Buffer.Data /= Null_Atom then Report.Item (Name, NT.Fail); Report.Info ("Data, returning an Atom"); Test_Tools.Dump_Atom (Report, Buffer.Data, "Found"); return; end if; if Buffer.Raw_Query.Data.all /= Null_Atom then Report.Item (Name, NT.Fail); Report.Info ("Raw_Query, returning an accessor"); Test_Tools.Dump_Atom (Report, Buffer.Raw_Query.Data.all, "Found"); return; end if; declare Retrieved : Atom (1 .. 10); Length : Count; begin Buffer.Read (Retrieved, Length); if Length /= 0 then Report.Item (Name, NT.Fail); Report.Info ("Read into an existing buffer"); Report.Info ("Length returned" & Count'Image (Length) & ", expected 0"); return; end if; end; declare procedure Check (Found : in Atom); Result : Boolean := False; procedure Check (Found : in Atom) is begin Result := Found = Null_Atom; end Check; begin Buffer.Query (Check'Access); if not Result then Report.Item (Name, NT.Fail); Report.Info ("Query with callback"); return; end if; end; end; Report.Item (Name, NT.Success); exception when Error : others => Report.Report_Exception (Name, Error); end Test_Query_Null; procedure Test_Reset (Report : in out NT.Reporter'Class) is Name : constant String := "Reset procedures"; begin declare Buffer : Atom_Buffer; begin for O in Octet loop Buffer.Append (O); end loop; declare Accessor : Atom_Refs.Accessor := Buffer.Raw_Query; begin Buffer.Soft_Reset; if Buffer.Length /= 0 then Report.Item (Name, NT.Fail); Report.Info ("Soft reset left length" & Count'Image (Buffer.Length)); return; end if; if Buffer.Raw_Query.Data /= Accessor.Data then Report.Item (Name, NT.Fail); Report.Info ("Soft reset changed storage area"); return; end if; if Buffer.Raw_Query.Data.all'Length /= Buffer.Capacity then Report.Item (Name, NT.Fail); Report.Info ("Available length inconsistency, recorded" & Count'Image (Buffer.Capacity) & ", actual" & Count'Image (Buffer.Raw_Query.Data.all'Length)); return; end if; if Buffer.Data'Length /= Buffer.Used then Report.Item (Name, NT.Fail); Report.Info ("Used length inconsistency, recorded" & Count'Image (Buffer.Used) & ", actual" & Count'Image (Buffer.Data'Length)); return; end if; end; for O in Octet'(10) .. Octet'(50) loop Buffer.Append (O); end loop; Buffer.Hard_Reset; if Buffer.Length /= 0 or else Buffer.Capacity /= 0 or else not Buffer.Ref.Is_Empty then Report.Item (Name, NT.Fail); Report.Info ("Hard reset did not completely clean structure"); end if; end; Report.Item (Name, NT.Success); exception when Error : others => Report.Report_Exception (Name, Error); end Test_Reset; procedure Test_Reverse_Append (Report : in out NT.Reporter'Class) is Name : constant String := "procedure Append_Reverse"; Source_1 : Atom (1 .. 10); Source_2 : Atom (1 .. 1); Source_3 : Atom (51 .. 65); Source_4 : Atom (1 .. 0); Source_5 : Atom (101 .. 114); Expected : Atom (1 .. 40); begin for I in Source_1'Range loop Source_1 (I) := 10 + Octet (I); Expected (Expected'First + Source_1'Last - I) := Source_1 (I); end loop; for I in Source_2'Range loop Source_2 (I) := 42; Expected (Expected'First + Source_1'Length + Source_2'Last - I) := Source_2 (I); end loop; for I in Source_3'Range loop Source_3 (I) := Octet (I); Expected (Expected'First + Source_1'Length + Source_2'Length + I - Source_3'First) := Source_3 (I); end loop; for I in Source_5'Range loop Source_5 (I) := Octet (I); Expected (Expected'First + Source_1'Length + Source_2'Length + Source_3'Length + Source_5'Last - I) := Source_5 (I); end loop; declare Buffer : Atom_Buffer; begin Buffer.Append_Reverse (Source_1); Buffer.Append_Reverse (Source_2); Buffer.Append (Source_3); Buffer.Append_Reverse (Source_4); Buffer.Append_Reverse (Source_5); Test_Tools.Test_Atom (Report, Name, Expected, Buffer.Data); end; exception when Error : others => Report.Report_Exception (Name, Error); end Test_Reverse_Append; procedure Test_Empty_Append (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Empty append on empty buffer"); begin declare Buffer : Atom_Buffer; begin Buffer.Append (Null_Atom); Test_Tools.Test_Atom (Test, Null_Atom, Buffer.Data); end; exception when Error : others => Test.Report_Exception (Error); end Test_Empty_Append; end Natools.S_Expressions.Atom_Buffers.Tests;
use the new capacity accessor in tests
s_expressions-atom_buffers-tests: use the new capacity accessor in tests
Ada
isc
faelys/natools
24dfb7f8eecfa8fe53547123f037bdb9d519b901
src/gen-artifacts-xmi.ads
src/gen-artifacts-xmi.ads
----------------------------------------------------------------------- -- gen-artifacts-xmi -- UML-XMI artifact for Code Generator -- 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 DOM.Core; with Gen.Model.Packages; with Gen.Model.XMI; -- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code -- from an UML XMI description. package Gen.Artifacts.XMI is -- ------------------------------ -- UML XMI artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. overriding procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Context : in out Generator'Class); -- Read the UML configuration files that define the pre-defined types, stereotypes -- and other components used by a model. These files are XMI files as well. -- All the XMI files in the UML config directory are read. procedure Read_UML_Configuration (Handler : in out Artifact; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with record Nodes : aliased Gen.Model.XMI.UML_Model; Has_Config : Boolean := False; -- Stereotype which triggers the generation of database table. Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Version_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; -- Tag definitions which control the generation. Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Sql_Type_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; -- Stereotype which triggers the generation of AWA bean types. Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; end record; end Gen.Artifacts.XMI;
----------------------------------------------------------------------- -- gen-artifacts-xmi -- UML-XMI artifact for Code Generator -- 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 DOM.Core; with Gen.Model.Packages; with Gen.Model.XMI; -- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code -- from an UML XMI description. package Gen.Artifacts.XMI is -- ------------------------------ -- UML XMI artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. overriding procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Context : in out Generator'Class); -- Read the UML configuration files that define the pre-defined types, stereotypes -- and other components used by a model. These files are XMI files as well. -- All the XMI files in the UML config directory are read. procedure Read_UML_Configuration (Handler : in out Artifact; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with record Nodes : aliased Gen.Model.XMI.UML_Model; Has_Config : Boolean := False; -- Stereotype which triggers the generation of database table. Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Version_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; -- Tag definitions which control the generation. Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Sql_Type_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Generator_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; -- Stereotype which triggers the generation of AWA bean types. Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; end record; end Gen.Artifacts.XMI;
Add the [email protected] tagged value definition
Add the [email protected] tagged value definition
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
359102683959ed88e87013c914236ab65cfe5338
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"); 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"); 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 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;
Add more tests on the wiki page verification
Add more tests on the wiki page verification
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
012dc4bd70fdfd05692dcf8de01d1bb8eefff8cc
awa/plugins/awa-workspaces/src/awa-workspaces.ads
awa/plugins/awa-workspaces/src/awa-workspaces.ads
----------------------------------------------------------------------- -- awa-workspaces -- Module workspaces -- 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. ----------------------------------------------------------------------- -- == Introduction == -- The *workspaces* plugin defines a workspace area for other plugins. -- -- == Data Model == -- @include Workspace.hbm.xml -- package AWA.Workspaces is end AWA.Workspaces;
----------------------------------------------------------------------- -- awa-workspaces -- Module workspaces -- 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. ----------------------------------------------------------------------- -- == Introduction == -- The *workspaces* plugin defines a workspace area for other plugins. -- -- == Ada Beans == -- @include workspaces.xml -- -- == Data Model == -- @include Workspace.hbm.xml -- package AWA.Workspaces is end AWA.Workspaces;
Add the Ada beans in the workspace documentation
Add the Ada beans in the workspace documentation
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
e990b1014da4871c41ab68abc022f0019f044902
awa/plugins/awa-jobs/src/awa-jobs.ads
awa/plugins/awa-jobs/src/awa-jobs.ads
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>AWA.Jobs</b> plugin defines a batch job framework for modules to perform and execute -- long running and deferred actions. The `Jobs` plugin is intended to help web application -- designers in implementing end to end asynchronous operation. A client schedules a job -- and does not block nor wait for the immediate completion. Instead, the client asks -- periodically or uses other mechanisms to check for the job completion. -- -- === Writing a job === -- A new job type is created by implementing the `Execute` operation of the abstract -- `Job_Type` tagged record. -- -- type Resize_Job is new AWA.Jobs.Job_Type with ...; -- -- The `Execute` procedure must be implemented. It should use the `Get_Parameter` functions -- to retrieve the job parameters and perform the work. While the job is being executed, -- it can save result by using the `Set_Result` operations, save messages by using the -- `Set_Message` operations and report the progress by using `Set_Progress`. -- It may report the job status by using `Set_Status`. -- -- procedure Execute (Job : in out Resize_Job) is -- begin -- Job.Set_Result ("done", "ok"); -- end Execute; -- -- === Registering a job === -- The <b>AWA.Jobs</b> plugin must be able to create the job instance when it is going to -- be executed. For this, a registration package must be instantiated: -- -- package Resize_Def is new AWA.Jobs.Definition (Resize_Job); -- -- and the job definition must be added: -- -- AWA.Jobs.Modules.Register (Resize_Def.Create'Access); -- -- === Scheduling a job === -- To schedule a job, declare an instance of the job to execute and set the job specific -- parameters. The job parameters will be saved in the database. As soon as parameters -- are defined, call the `Schedule` procedure to schedule the job in the job queue and -- obtain a job identifier. -- -- Resize : Resize_Job; -- ... -- Resize.Set_Parameter ("file", "image.png"); -- Resize.Set_Parameter ("width", "32"); -- Resize.Set_Parameter ("height, "32"); -- Resize.Schedule; -- -- === Checking for job completion === -- -- -- == Data Model == -- @include jobs.hbm.xml -- package AWA.Jobs is end AWA.Jobs;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>AWA.Jobs</b> plugin defines a batch job framework for modules to perform and execute -- long running and deferred actions. The `Jobs` plugin is intended to help web application -- designers in implementing end to end asynchronous operation. A client schedules a job -- and does not block nor wait for the immediate completion. Instead, the client asks -- periodically or uses other mechanisms to check for the job completion. -- -- === Writing a job === -- A new job type is created by implementing the `Execute` operation of the abstract -- `Job_Type` tagged record. -- -- type Resize_Job is new AWA.Jobs.Job_Type with ...; -- -- The `Execute` procedure must be implemented. It should use the `Get_Parameter` functions -- to retrieve the job parameters and perform the work. While the job is being executed, -- it can save result by using the `Set_Result` operations, save messages by using the -- `Set_Message` operations and report the progress by using `Set_Progress`. -- It may report the job status by using `Set_Status`. -- -- procedure Execute (Job : in out Resize_Job) is -- begin -- Job.Set_Result ("done", "ok"); -- end Execute; -- -- === Registering a job === -- The <b>AWA.Jobs</b> plugin must be able to create the job instance when it is going to -- be executed. For this, a registration package must be instantiated: -- -- package Resize_Def is new AWA.Jobs.Definition (Resize_Job); -- -- and the job definition must be added: -- -- AWA.Jobs.Modules.Register (Resize_Def.Create'Access); -- -- === Scheduling a job === -- To schedule a job, declare an instance of the job to execute and set the job specific -- parameters. The job parameters will be saved in the database. As soon as parameters -- are defined, call the `Schedule` procedure to schedule the job in the job queue and -- obtain a job identifier. -- -- Resize : Resize_Job; -- ... -- Resize.Set_Parameter ("file", "image.png"); -- Resize.Set_Parameter ("width", "32"); -- Resize.Set_Parameter ("height, "32"); -- Resize.Schedule; -- -- === Checking for job completion === -- -- -- @include awa-jobs-modules.ads -- -- == Data Model == -- @include jobs.hbm.xml -- package AWA.Jobs is end AWA.Jobs;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
011edfcf97a12d64984f2860ac83205c4525872b
src/gen-model-xmi.ads
src/gen-model-xmi.ads
----------------------------------------------------------------------- -- gen-model-xmi -- UML-XMI model -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Vectors; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.XMI is use Ada.Strings.Unbounded; type Element_Type is (XMI_UNKNOWN, XMI_PACKAGE, XMI_CLASS, XMI_ASSOCIATION, XMI_ASSOCIATION_END, XMI_ATTRIBUTE, XMI_OPERATION, XMI_ENUMERATION, XMI_ENUMERATION_LITERAL, XMI_TAGGED_VALUE, XMI_TAG_DEFINITION, XMI_DATA_TYPE, XMI_STEREOTYPE, XMI_COMMENT); type Visibility_Type is (VISIBILITY_PUBLIC, VISIBILITY_PACKAGE, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE); type Changeability_Type is (CHANGEABILITY_INSERT, CHANGEABILITY_CHANGEABLE, CHANGEABILITY_FROZEN); type Model_Element; type Tagged_Value_Element; type Model_Element_Access is access all Model_Element'Class; type Tagged_Value_Element_Access is access all Tagged_Value_Element'Class; -- Define a list of model elements. package Model_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Model_Element_Access); subtype Model_Vector is Model_Vectors.Vector; subtype Model_Cursor is Model_Vectors.Cursor; -- Define a map to search an element from its XMI ID. package Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Element_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Model_Map_Cursor is Model_Map.Cursor; type Model_Map_Access is access all Model_Map.Map; -- Returns true if the table cursor contains a valid table function Has_Element (Position : in Model_Map_Cursor) return Boolean renames Model_Map.Has_Element; -- Returns the table definition. function Element (Position : in Model_Map_Cursor) return Model_Element_Access renames Model_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Model_Map_Cursor) renames Model_Map.Next; -- Iterate on the model element of the type <tt>On</tt> and execute the <tt>Process</tt> -- procedure. procedure Iterate (Model : in Model_Map.Map; On : in Element_Type; Process : not null access procedure (Id : in Unbounded_String; Node : in Model_Element_Access)); -- Generic procedure to iterate over the XMI elements of a vector -- and having the entity name <b>name</b>. generic type T (<>) is limited private; procedure Iterate_Elements (Closure : in out T; List : in Model_Vector; Process : not null access procedure (Closure : in out T; Node : in Model_Element_Access)); -- Map of UML models indexed on the model name. package UML_Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Map.Map, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => Model_Map."="); subtype UML_Model is UML_Model_Map.Map; type Search_Type is (BY_NAME, BY_ID); -- Find the model element with the given XMI id. -- Returns null if the model element is not found. function Find (Model : in Model_Map.Map; Key : in String; Mode : in Search_Type := BY_ID) return Model_Element_Access; -- Find the model element within all loaded UML models. -- Returns null if the model element is not found. function Find (Model : in UML_Model; Current : in Model_Map.Map; Id : in Ada.Strings.Unbounded.Unbounded_String) return Model_Element_Access; -- Dump the XMI model elements. procedure Dump (Map : in Model_Map.Map); -- Reconcile all the UML model elements by resolving all the references to UML elements. procedure Reconcile (Model : in out UML_Model); -- ------------------------------ -- Model Element -- ------------------------------ type Model_Element (Model : Model_Map_Access) is abstract new Definition with record -- Element XMI id. XMI_Id : Ada.Strings.Unbounded.Unbounded_String; -- List of tagged values for the element. Tagged_Values : Model_Vector; -- Elements contained. Elements : Model_Vector; -- Stereotypes associated with the element. Stereotypes : Model_Vector; -- The parent model element; Parent : Model_Element_Access; end record; -- Get the element type. function Get_Type (Node : in Model_Element) return Element_Type is abstract; -- Reconcile the element by resolving the references to other elements in the model. procedure Reconcile (Node : in out Model_Element; Model : in UML_Model); -- Find the element with the given name. If the name is a qualified name, navigate -- down the package/class to find the appropriate element. -- Returns null if the element was not found. function Find (Node : in Model_Element; Name : in String) return Model_Element_Access; -- Set the model name. procedure Set_Name (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Set the model XMI unique id. procedure Set_XMI_Id (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Find the tag value element with the given name. -- Returns null if there is no such tag. function Find_Tag_Value (Node : in Model_Element; Name : in String) return Tagged_Value_Element_Access; -- Get the documentation and comment associated with the model element. -- Returns the empty string if there is no comment. function Get_Comment (Node : in Model_Element) return String; -- Get the full qualified name for the element. function Get_Qualified_Name (Node : in Model_Element) return String; -- Find from the model file identified by <tt>Name</tt>, the model element with the -- identifier or name represented by <tt>Key</tt>. -- Returns null if the model element is not found. generic type Element_Type is new Model_Element with private; type Element_Type_Access is access all Element_Type'Class; function Find_Element (Model : in UML_Model; Name : in String; Key : in String; Mode : in Search_Type := BY_ID) return Element_Type_Access; -- ------------------------------ -- Data type -- ------------------------------ type Ref_Type_Element is new Model_Element with record Href : Unbounded_String; Ref : Model_Element_Access; end record; type Ref_Type_Element_Access is access all Ref_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Ref_Type_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Ref_Type_Element; Model : in UML_Model); -- ------------------------------ -- Data type -- ------------------------------ type Data_Type_Element is new Model_Element with null record; type Data_Type_Element_Access is access all Data_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Data_Type_Element) return Element_Type; -- ------------------------------ -- Enum -- ------------------------------ type Enum_Element is new Model_Element with null record; type Enum_Element_Access is access all Enum_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Enum_Element) return Element_Type; procedure Add_Literal (Node : in out Enum_Element; Id : in Util.Beans.Objects.Object; Name : in Util.Beans.Objects.Object); -- ------------------------------ -- Literal -- ------------------------------ -- The literal describes a possible value for an enum. type Literal_Element is new Model_Element with null record; type Literal_Element_Access is access all Literal_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Literal_Element) return Element_Type; -- ------------------------------ -- Stereotype -- ------------------------------ type Stereotype_Element is new Model_Element with null record; type Stereotype_Element_Access is access all Stereotype_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Stereotype_Element) return Element_Type; -- Returns True if the model element has the stereotype with the given name. function Has_Stereotype (Node : in Model_Element'Class; Stereotype : in Stereotype_Element_Access) return Boolean; -- ------------------------------ -- Comment -- ------------------------------ type Comment_Element is new Model_Element with record Text : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; end record; type Comment_Element_Access is access all Comment_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Comment_Element) return Element_Type; -- ------------------------------ -- An operation -- ------------------------------ type Operation_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Operation_Element_Access is access all Operation_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Operation_Element) return Element_Type; -- ------------------------------ -- An attribute -- ------------------------------ type Attribute_Element is new Model_Element with record Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Visibility : Visibility_Type := VISIBILITY_PUBLIC; Changeability : Changeability_Type := CHANGEABILITY_CHANGEABLE; Initial_Value : Util.Beans.Objects.Object; Multiplicity_Lower : Integer := 0; Multiplicity_Upper : Integer := 1; end record; type Attribute_Element_Access is access all Attribute_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Attribute_Element) return Element_Type; -- ------------------------------ -- An association end -- ------------------------------ type Association_End_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_End_Element_Access is access all Association_End_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_End_Element) return Element_Type; -- ------------------------------ -- An association -- ------------------------------ type Association_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_Element_Access is access all Association_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_Element) return Element_Type; -- ------------------------------ -- Tag Definition -- ------------------------------ TAG_DOCUMENTATION : constant String := "documentation"; TAG_AUTHOR : constant String := "author"; type Tag_Definition_Element is new Model_Element with record Multiplicity_Lower : Natural := 0; Multiplicity_Upper : Natural := 0; end record; type Tag_Definition_Element_Access is access all Tag_Definition_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Tag_Definition_Element) return Element_Type; -- ------------------------------ -- Tagged value -- ------------------------------ type Tagged_Value_Element is new Model_Element with record Value : Ada.Strings.Unbounded.Unbounded_String; Value_Type : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Tag_Def : Tag_Definition_Element_Access; end record; -- Get the element type. overriding function Get_Type (Node : in Tagged_Value_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Tagged_Value_Element; Model : in UML_Model); -- ------------------------------ -- A class -- ------------------------------ type Class_Element is new Model_Element with record Operations : Model_Vector; Attributes : Model_Vector; Associations : Model_Vector; Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Class_Element_Access is access all Class_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Class_Element) return Element_Type; -- ------------------------------ -- A package -- ------------------------------ type Package_Element; type Package_Element_Access is access all Package_Element'Class; type Package_Element is new Model_Element with record Classes : Model_Vector; end record; -- Get the element type. overriding function Get_Type (Node : in Package_Element) return Element_Type; end Gen.Model.XMI;
----------------------------------------------------------------------- -- gen-model-xmi -- UML-XMI model -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Vectors; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.XMI is use Ada.Strings.Unbounded; type Element_Type is (XMI_UNKNOWN, XMI_PACKAGE, XMI_CLASS, XMI_ASSOCIATION, XMI_ASSOCIATION_END, XMI_ATTRIBUTE, XMI_OPERATION, XMI_ENUMERATION, XMI_ENUMERATION_LITERAL, XMI_TAGGED_VALUE, XMI_TAG_DEFINITION, XMI_DATA_TYPE, XMI_STEREOTYPE, XMI_COMMENT); -- Defines the visibility of an element (a package, class, attribute, operation). type Visibility_Type is (VISIBILITY_PUBLIC, VISIBILITY_PACKAGE, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE); -- Defines whether an attribute or association changes. type Changeability_Type is (CHANGEABILITY_INSERT, CHANGEABILITY_CHANGEABLE, CHANGEABILITY_FROZEN); type Model_Element; type Tagged_Value_Element; type Model_Element_Access is access all Model_Element'Class; type Tagged_Value_Element_Access is access all Tagged_Value_Element'Class; -- Define a list of model elements. package Model_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Model_Element_Access); subtype Model_Vector is Model_Vectors.Vector; subtype Model_Cursor is Model_Vectors.Cursor; -- Define a map to search an element from its XMI ID. package Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Element_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Model_Map_Cursor is Model_Map.Cursor; type Model_Map_Access is access all Model_Map.Map; -- Returns true if the table cursor contains a valid table function Has_Element (Position : in Model_Map_Cursor) return Boolean renames Model_Map.Has_Element; -- Returns the table definition. function Element (Position : in Model_Map_Cursor) return Model_Element_Access renames Model_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Model_Map_Cursor) renames Model_Map.Next; -- Iterate on the model element of the type <tt>On</tt> and execute the <tt>Process</tt> -- procedure. procedure Iterate (Model : in Model_Map.Map; On : in Element_Type; Process : not null access procedure (Id : in Unbounded_String; Node : in Model_Element_Access)); -- Generic procedure to iterate over the XMI elements of a vector -- and having the entity name <b>name</b>. generic type T (<>) is limited private; procedure Iterate_Elements (Closure : in out T; List : in Model_Vector; Process : not null access procedure (Closure : in out T; Node : in Model_Element_Access)); -- Map of UML models indexed on the model name. package UML_Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Map.Map, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => Model_Map."="); subtype UML_Model is UML_Model_Map.Map; type Search_Type is (BY_NAME, BY_ID); -- Find the model element with the given XMI id. -- Returns null if the model element is not found. function Find (Model : in Model_Map.Map; Key : in String; Mode : in Search_Type := BY_ID) return Model_Element_Access; -- Find the model element within all loaded UML models. -- Returns null if the model element is not found. function Find (Model : in UML_Model; Current : in Model_Map.Map; Id : in Ada.Strings.Unbounded.Unbounded_String) return Model_Element_Access; -- Dump the XMI model elements. procedure Dump (Map : in Model_Map.Map); -- Reconcile all the UML model elements by resolving all the references to UML elements. procedure Reconcile (Model : in out UML_Model); -- ------------------------------ -- Model Element -- ------------------------------ type Model_Element (Model : Model_Map_Access) is abstract new Definition with record -- Element XMI id. XMI_Id : Ada.Strings.Unbounded.Unbounded_String; -- List of tagged values for the element. Tagged_Values : Model_Vector; -- Elements contained. Elements : Model_Vector; -- Stereotypes associated with the element. Stereotypes : Model_Vector; -- The parent model element; Parent : Model_Element_Access; end record; -- Get the element type. function Get_Type (Node : in Model_Element) return Element_Type is abstract; -- Reconcile the element by resolving the references to other elements in the model. procedure Reconcile (Node : in out Model_Element; Model : in UML_Model); -- Find the element with the given name. If the name is a qualified name, navigate -- down the package/class to find the appropriate element. -- Returns null if the element was not found. function Find (Node : in Model_Element; Name : in String) return Model_Element_Access; -- Set the model name. procedure Set_Name (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Set the model XMI unique id. procedure Set_XMI_Id (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Find the tag value element with the given name. -- Returns null if there is no such tag. function Find_Tag_Value (Node : in Model_Element; Name : in String) return Tagged_Value_Element_Access; -- Get the documentation and comment associated with the model element. -- Returns the empty string if there is no comment. function Get_Comment (Node : in Model_Element) return String; -- Get the full qualified name for the element. function Get_Qualified_Name (Node : in Model_Element) return String; -- Find from the model file identified by <tt>Name</tt>, the model element with the -- identifier or name represented by <tt>Key</tt>. -- Returns null if the model element is not found. generic type Element_Type is new Model_Element with private; type Element_Type_Access is access all Element_Type'Class; function Find_Element (Model : in UML_Model; Name : in String; Key : in String; Mode : in Search_Type := BY_ID) return Element_Type_Access; -- ------------------------------ -- Data type -- ------------------------------ type Ref_Type_Element is new Model_Element with record Href : Unbounded_String; Ref : Model_Element_Access; end record; type Ref_Type_Element_Access is access all Ref_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Ref_Type_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Ref_Type_Element; Model : in UML_Model); -- ------------------------------ -- Data type -- ------------------------------ type Data_Type_Element is new Model_Element with null record; type Data_Type_Element_Access is access all Data_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Data_Type_Element) return Element_Type; -- ------------------------------ -- Enum -- ------------------------------ type Enum_Element is new Model_Element with null record; type Enum_Element_Access is access all Enum_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Enum_Element) return Element_Type; procedure Add_Literal (Node : in out Enum_Element; Id : in Util.Beans.Objects.Object; Name : in Util.Beans.Objects.Object); -- ------------------------------ -- Literal -- ------------------------------ -- The literal describes a possible value for an enum. type Literal_Element is new Model_Element with null record; type Literal_Element_Access is access all Literal_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Literal_Element) return Element_Type; -- ------------------------------ -- Stereotype -- ------------------------------ type Stereotype_Element is new Model_Element with null record; type Stereotype_Element_Access is access all Stereotype_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Stereotype_Element) return Element_Type; -- Returns True if the model element has the stereotype with the given name. function Has_Stereotype (Node : in Model_Element'Class; Stereotype : in Stereotype_Element_Access) return Boolean; -- ------------------------------ -- Comment -- ------------------------------ type Comment_Element is new Model_Element with record Text : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; end record; type Comment_Element_Access is access all Comment_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Comment_Element) return Element_Type; -- ------------------------------ -- An operation -- ------------------------------ type Operation_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Operation_Element_Access is access all Operation_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Operation_Element) return Element_Type; -- ------------------------------ -- An attribute -- ------------------------------ type Attribute_Element is new Model_Element with record Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Visibility : Visibility_Type := VISIBILITY_PUBLIC; Changeability : Changeability_Type := CHANGEABILITY_CHANGEABLE; Initial_Value : Util.Beans.Objects.Object; Multiplicity_Lower : Integer := 0; Multiplicity_Upper : Integer := 1; end record; type Attribute_Element_Access is access all Attribute_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Attribute_Element) return Element_Type; -- ------------------------------ -- An association end -- ------------------------------ type Association_End_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_End_Element_Access is access all Association_End_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_End_Element) return Element_Type; -- ------------------------------ -- An association -- ------------------------------ type Association_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_Element_Access is access all Association_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_Element) return Element_Type; -- ------------------------------ -- Tag Definition -- ------------------------------ TAG_DOCUMENTATION : constant String := "documentation"; TAG_AUTHOR : constant String := "author"; type Tag_Definition_Element is new Model_Element with record Multiplicity_Lower : Natural := 0; Multiplicity_Upper : Natural := 0; end record; type Tag_Definition_Element_Access is access all Tag_Definition_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Tag_Definition_Element) return Element_Type; -- ------------------------------ -- Tagged value -- ------------------------------ type Tagged_Value_Element is new Model_Element with record Value : Ada.Strings.Unbounded.Unbounded_String; Value_Type : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Tag_Def : Tag_Definition_Element_Access; end record; -- Get the element type. overriding function Get_Type (Node : in Tagged_Value_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Tagged_Value_Element; Model : in UML_Model); -- ------------------------------ -- A class -- ------------------------------ type Class_Element is new Model_Element with record Operations : Model_Vector; Attributes : Model_Vector; Associations : Model_Vector; Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Class_Element_Access is access all Class_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Class_Element) return Element_Type; -- ------------------------------ -- A package -- ------------------------------ type Package_Element; type Package_Element_Access is access all Package_Element'Class; type Package_Element is new Model_Element with record Classes : Model_Vector; end record; -- Get the element type. overriding function Get_Type (Node : in Package_Element) return Element_Type; end Gen.Model.XMI;
Add some comments.
Add some comments.
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
0b34b35ce477b31573529b60f8bf2f4eab3c0138
src/base/beans/util-beans-objects-time.ads
src/base/beans/util-beans-objects-time.ads
----------------------------------------------------------------------- -- Util.Beans.Objects.Time -- Helper conversion for Ada Calendar Time -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; package Util.Beans.Objects.Time is -- Create an object from the given value. function To_Object (Value : in Ada.Calendar.Time) return Object; -- Convert the object into a time. -- Raises Constraint_Error if the object cannot be converter to the target type. function To_Time (Value : in Object) return Ada.Calendar.Time; -- Force the object to be a time. function Cast_Time (Value : Object) return Object; end Util.Beans.Objects.Time;
----------------------------------------------------------------------- -- util-beans-objects-time -- Helper conversion for Ada Calendar Time -- Copyright (C) 2010, 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.Calendar; with Util.Nullables; package Util.Beans.Objects.Time is -- Create an object from the given value. function To_Object (Value : in Ada.Calendar.Time) return Object; function To_Object (Value : in Nullables.Nullable_Time) return Object; -- Convert the object into a time. -- Raises Constraint_Error if the object cannot be converter to the target type. function To_Time (Value : in Object) return Ada.Calendar.Time; function To_Time (Value : in Object) return Nullables.Nullable_Time; -- Force the object to be a time. function Cast_Time (Value : Object) return Object; end Util.Beans.Objects.Time;
Add To_Object and To_Time with a Nullable_Time type
Add To_Object and To_Time with a Nullable_Time type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
61a42e9902a2647a6796b1056708fc670f5c6222
src/util-serialize-io.ads
src/util-serialize-io.ads
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Streams; with Util.Streams.Buffered; with Util.Serialize.Contexts; with Util.Serialize.Mappers; with Util.Log.Loggers; with Util.Stacks; package Util.Serialize.IO is Parse_Error : exception; -- ------------------------------ -- Output stream for serialization -- ------------------------------ -- The <b>Output_Stream</b> interface defines the abstract operations for -- the serialization framework to write objects on the stream according to -- a target format such as XML or JSON. type Output_Stream is limited interface and Util.Streams.Output_Stream; -- Start a document. procedure Start_Document (Stream : in out Output_Stream) is null; -- Finish a document. procedure End_Document (Stream : in out Output_Stream) is null; procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is null; procedure End_Entity (Stream : in out Output_Stream; Name : in String) is null; -- Write the attribute name/value pair. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); -- Write the entity value. procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Start_Array (Stream : in out Output_Stream; Name : in String) is null; procedure End_Array (Stream : in out Output_Stream; Name : in String) is null; type Parser is abstract new Util.Serialize.Contexts.Context with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is abstract; -- Read the file and parse it using the parser. procedure Parse (Handler : in out Parser; File : in String); -- Parse the content string. procedure Parse_String (Handler : in out Parser; Content : in String); -- Returns true if the <b>Parse</b> operation detected at least one error. function Has_Error (Handler : in Parser) return Boolean; -- Set the error logger to report messages while parsing and reading the input file. procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access); -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. procedure Start_Object (Handler : in out Parser; Name : in String); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. procedure Finish_Object (Handler : in out Parser; Name : in String); procedure Start_Array (Handler : in out Parser; Name : in String); procedure Finish_Array (Handler : in out Parser; Name : in String); -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. procedure Set_Member (Handler : in out Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. procedure Error (Handler : in out Parser; Message : in String); procedure Add_Mapping (Handler : in out Parser; Path : in String; Mapper : in Util.Serialize.Mappers.Mapper_Access); -- Dump the mapping tree on the logger using the INFO log level. procedure Dump (Handler : in Parser'Class; Logger : in Util.Log.Loggers.Logger'Class); private -- Implementation limitation: the max number of active mapping nodes MAX_NODES : constant Positive := 10; type Mapper_Access_Array is array (1 .. MAX_NODES) of Serialize.Mappers.Mapper_Access; procedure Push (Handler : in out Parser); -- Pop the context and restore the previous context when leaving an element procedure Pop (Handler : in out Parser); function Find_Mapper (Handler : in Parser; Name : in String) return Util.Serialize.Mappers.Mapper_Access; type Element_Context is record -- The object mapper being process. Object_Mapper : Util.Serialize.Mappers.Mapper_Access; -- The active mapping nodes. Active_Nodes : Mapper_Access_Array; end record; type Element_Context_Access is access all Element_Context; package Context_Stack is new Util.Stacks (Element_Type => Element_Context, Element_Type_Access => Element_Context_Access); type Parser is abstract new Util.Serialize.Contexts.Context with record Error_Flag : Boolean := False; Stack : Context_Stack.Stack; Mapping_Tree : aliased Mappers.Mapper; Current_Mapper : Util.Serialize.Mappers.Mapper_Access; -- The file name to use when reporting errors. File : Ada.Strings.Unbounded.Unbounded_String; -- The logger which is used to report error messages when parsing an input file. Error_Logger : Util.Log.Loggers.Logger_Access := null; end record; end Util.Serialize.IO;
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Streams; with Util.Streams.Buffered; with Util.Serialize.Contexts; with Util.Serialize.Mappers; with Util.Log.Loggers; with Util.Stacks; package Util.Serialize.IO is Parse_Error : exception; -- ------------------------------ -- Output stream for serialization -- ------------------------------ -- The <b>Output_Stream</b> interface defines the abstract operations for -- the serialization framework to write objects on the stream according to -- a target format such as XML or JSON. type Output_Stream is limited interface and Util.Streams.Output_Stream; -- Start a document. procedure Start_Document (Stream : in out Output_Stream) is null; -- Finish a document. procedure End_Document (Stream : in out Output_Stream) is null; procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is null; procedure End_Entity (Stream : in out Output_Stream; Name : in String) is null; -- Write the attribute name/value pair. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); -- Write the entity value. procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is abstract; procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Start_Array (Stream : in out Output_Stream; Name : in String) is null; procedure End_Array (Stream : in out Output_Stream; Name : in String) is null; type Parser is abstract new Util.Serialize.Contexts.Context with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is abstract; -- Read the file and parse it using the parser. procedure Parse (Handler : in out Parser; File : in String); -- Parse the content string. procedure Parse_String (Handler : in out Parser; Content : in String); -- Returns true if the <b>Parse</b> operation detected at least one error. function Has_Error (Handler : in Parser) return Boolean; -- Set the error logger to report messages while parsing and reading the input file. procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access); -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. procedure Start_Object (Handler : in out Parser; Name : in String); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. procedure Finish_Object (Handler : in out Parser; Name : in String); procedure Start_Array (Handler : in out Parser; Name : in String); procedure Finish_Array (Handler : in out Parser; Name : in String); -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. procedure Set_Member (Handler : in out Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. procedure Error (Handler : in out Parser; Message : in String); procedure Add_Mapping (Handler : in out Parser; Path : in String; Mapper : in Util.Serialize.Mappers.Mapper_Access); -- Dump the mapping tree on the logger using the INFO log level. procedure Dump (Handler : in Parser'Class; Logger : in Util.Log.Loggers.Logger'Class); private -- Implementation limitation: the max number of active mapping nodes MAX_NODES : constant Positive := 10; type Mapper_Access_Array is array (1 .. MAX_NODES) of Serialize.Mappers.Mapper_Access; procedure Push (Handler : in out Parser); -- Pop the context and restore the previous context when leaving an element procedure Pop (Handler : in out Parser); function Find_Mapper (Handler : in Parser; Name : in String) return Util.Serialize.Mappers.Mapper_Access; type Element_Context is record -- The object mapper being process. Object_Mapper : Util.Serialize.Mappers.Mapper_Access; -- The active mapping nodes. Active_Nodes : Mapper_Access_Array; end record; type Element_Context_Access is access all Element_Context; package Context_Stack is new Util.Stacks (Element_Type => Element_Context, Element_Type_Access => Element_Context_Access); type Parser is abstract new Util.Serialize.Contexts.Context with record Error_Flag : Boolean := False; Stack : Context_Stack.Stack; Mapping_Tree : aliased Mappers.Mapper; Current_Mapper : Util.Serialize.Mappers.Mapper_Access; -- The file name to use when reporting errors. File : Ada.Strings.Unbounded.Unbounded_String; -- The logger which is used to report error messages when parsing an input file. Error_Logger : Util.Log.Loggers.Logger_Access := null; end record; end Util.Serialize.IO;
Declare the Write_Enum_Entity for enum image value serialization
Declare the Write_Enum_Entity for enum image value serialization
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
89230f36d0508bd44b28863bca949ca9d9b46a09
src/wiki-render-links.ads
src/wiki-render-links.ads
----------------------------------------------------------------------- -- wiki-render-links -- Wiki links renderering -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; -- === Link Renderer === -- The <tt>Wiki.Render.Links</tt> package defines the <tt>Link_Renderer</tt> interface used -- for the rendering of links and images. The interface allows to customize the generated -- links and image source for the final HTML. -- package Wiki.Render.Links is pragma Preelaborate; type Link_Renderer is limited interface; type Link_Renderer_Access is access all Link_Renderer'Class; -- Get the image link that must be rendered from the wiki image link. procedure Make_Image_Link (Renderer : in out Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Width : out Natural; Height : out Natural) is abstract; -- Get the page link that must be rendered from the wiki page link. procedure Make_Page_Link (Renderer : in out Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Exists : out Boolean) is abstract; type Default_Link_Renderer is new Link_Renderer with null record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; 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 Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Exists : out Boolean); end Wiki.Render.Links;
----------------------------------------------------------------------- -- wiki-render-links -- Wiki links renderering -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; -- === Link Renderer === -- The <tt>Wiki.Render.Links</tt> package defines the <tt>Link_Renderer</tt> interface used -- for the rendering of links and images. The interface allows to customize the generated -- links and image source for the final HTML. -- package Wiki.Render.Links is pragma Preelaborate; type Link_Renderer is limited interface; type Link_Renderer_Access is access all Link_Renderer'Class; -- Get the image link that must be rendered from the wiki image link. procedure Make_Image_Link (Renderer : in out Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Width : in out Natural; Height : in out Natural) is abstract; -- Get the page link that must be rendered from the wiki page link. procedure Make_Page_Link (Renderer : in out Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Exists : out Boolean) is abstract; type Default_Link_Renderer is new Link_Renderer with null record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Width : in out Natural; Height : in out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in out Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Exists : out Boolean); end Wiki.Render.Links;
Change the Make_Image_Link width and height parameters as in out. Before the call, the width/height represent the expected size and upon result they represent the final image size (when known and after scaling)
Change the Make_Image_Link width and height parameters as in out. Before the call, the width/height represent the expected size and upon result they represent the final image size (when known and after scaling)
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
142fa3a09c9195cc09fab5342b6e43e8fa0c9ef5
src/wiki-streams-html.ads
src/wiki-streams-html.ads
----------------------------------------------------------------------- -- wiki-streams-html -- Wiki HTML output stream -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Strings; -- == Writer interfaces == -- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write -- their outputs. -- -- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to -- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser -- repeatedly while scanning the Wiki content. package Wiki.Streams.Html is use Ada.Strings.Wide_Wide_Unbounded; type Html_Output_Stream_Type is limited interface and Output_Stream; type Html_Output_Stream_Access is access all Html_Output_Stream_Type'Class; -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wide_Wide_String) is abstract; -- Start an XML element with the given name. procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is abstract; -- Closes an XML element of the given name. procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is abstract; -- Write a text escaping any character as necessary. procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Writer : in out Html_Writer_Type'Class; Name : in String; Content : in String); end Wiki.Streams.Html;
----------------------------------------------------------------------- -- wiki-streams-html -- Wiki HTML output stream -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Strings; -- == Writer interfaces == -- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write -- their outputs. -- -- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to -- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser -- repeatedly while scanning the Wiki content. package Wiki.Streams.Html is use Ada.Strings.Wide_Wide_Unbounded; type Html_Output_Stream_Type is limited interface and Output_Stream; type Html_Output_Stream_Access is access all Html_Output_Stream_Type'Class; -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Wide_Element (Writer : in out Html_Output_Stream_Type; Name : in String; Content : in Wiki.Strings.WString) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream_Type; Name : in String; Content : in Wide_Wide_String) is abstract; -- Start an XML element with the given name. procedure Start_Element (Writer : in out Html_Output_Stream_Type; Name : in String) is abstract; -- Closes an XML element of the given name. procedure End_Element (Writer : in out Html_Output_Stream_Type; Name : in String) is abstract; -- Write a text escaping any character as necessary. procedure Write_Wide_Text (Writer : in out Html_Output_Stream_Type; Content : in Wiki.Strings.WString) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Writer : in out Html_Output_Stream_Type'Class; Name : in String; Content : in String); end Wiki.Streams.Html;
Use Html_Output_Stream_Type for interface operations
Use Html_Output_Stream_Type for interface operations
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
2057939ba4499493e11cdcc0a0c30ebd2be7c7a5
testutil/aunit/util-tests-reporter.adb
testutil/aunit/util-tests-reporter.adb
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- A U N I T . R E P O R T E R . X M L -- -- -- -- B o d y -- -- -- -- -- -- Copyright (C) 2000-2009, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT 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 distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- GNAT is maintained by AdaCore (http://www.adacore.com) -- -- -- ------------------------------------------------------------------------------ with Util.Strings; with Util.Strings.Transforms; with AUnit.Time_Measure; -- Very simple reporter to console package body Util.Tests.Reporter is use AUnit.Test_Results; use type AUnit.Message_String; use type AUnit.Time_Measure.Time; use Ada.Text_IO; procedure Print_Summary (R : in out Result'Class); procedure Dump_Result_List (File : in Ada.Text_IO.File_Type; L : in Result_Lists.List); -- List failed assertions -- procedure Put_Measure is new Gen_Put_Measure; -- Output elapsed time procedure Report_Test (File : in Ada.Text_IO.File_Type; Test : in Test_Result); -- Report a single assertion failure or unexpected exception procedure Put (File : in Ada.Text_IO.File_Type; I : in Integer); procedure Put (File : in Ada.Text_IO.File_Type; T : in AUnit.Time_Measure.Time); procedure Put (File : in Ada.Text_IO.File_Type; I : in Integer) is begin Ada.Text_IO.Put (File, Util.Strings.Image (I)); end Put; procedure Put (File : in Ada.Text_IO.File_Type; T : in AUnit.Time_Measure.Time) is use Ada.Calendar; D : constant Duration := T.Stop - T.Start; S : constant String := Duration'Image (D); Pos : Natural := S'Last; begin while Pos > S'First and S (Pos) = '0' loop Pos := Pos - 1; end loop; if D >= 0.0 then Put (File, S (S'First + 1 .. Pos)); else Put (File, S (S'First .. Pos)); end if; end Put; ---------------------- -- Dump_Result_List -- ---------------------- procedure Dump_Result_List (File : in Ada.Text_IO.File_Type; L : in Result_Lists.List) is use Result_Lists; C : Cursor := First (L); begin -- Note: can't use Iterate because it violates restriction -- No_Implicit_Dynamic_Code while Has_Element (C) loop Report_Test (File, Element (C)); Next (C); end loop; end Dump_Result_List; ------------ -- Report -- ------------ procedure Report (Engine : XML_Reporter; R : in out Result'Class) is Output : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Output, Mode => Ada.Text_IO.Out_File, Name => To_String (Engine.File)); Engine.Report (Output, R); Ada.Text_IO.Close (Output); end Report; procedure Print_Summary (R : in out Result'Class) is S_Count : constant Integer := Integer (Success_Count (R)); F_Count : constant Integer := Integer (Failure_Count (R)); E_Count : constant Integer := Integer (Error_Count (R)); begin New_Line; Put ("Total Tests Run: "); Put (Util.Strings.Image (Integer (Test_Count (R)))); New_Line; Put ("Successful Tests: "); Put (Util.Strings.Image (S_Count)); New_Line; Put ("Failed Assertions: "); Put (Util.Strings.Image (F_Count)); New_Line; Put ("Unexpected Errors: "); Put (Util.Strings.Image (E_Count)); New_Line; end Print_Summary; ------------ -- Report -- ------------ procedure Report (Engine : XML_Reporter; File : in out Ada.Text_IO.File_Type; R : in out Result'Class) is pragma Unreferenced (Engine); begin Put_Line (File, "<?xml version='1.0' encoding='utf-8' ?>"); Put (File, "<TestRun"); if Elapsed (R) /= AUnit.Time_Measure.Null_Time then Put (File, " elapsed='"); Put (File, Elapsed (R)); Put_Line (File, "'>"); else Put_Line (File, ">"); end if; Print_Summary (R); Put_Line (File, " <Statistics>"); Put (File, " <Tests>"); Put (File, Integer (Test_Count (R))); Put_Line (File, "</Tests>"); Put (File, " <FailuresTotal>"); Put (File, Integer (Failure_Count (R)) + Integer (Error_Count (R))); Put_Line (File, "</FailuresTotal>"); Put (File, " <Failures>"); Put (File, Integer (Failure_Count (R))); Put_Line (File, "</Failures>"); Put (File, " <Errors>"); Put (File, Integer (Error_Count (R))); Put_Line (File, "</Errors>"); Put_Line (File, " </Statistics>"); declare S : Result_Lists.List; begin Put_Line (File, " <SuccessfulTests>"); Successes (R, S); Dump_Result_List (File, S); Put_Line (File, " </SuccessfulTests>"); end; Put_Line (File, " <FailedTests>"); declare F : Result_Lists.List; begin Failures (R, F); Dump_Result_List (File, F); end; declare E : Result_Lists.List; begin Errors (R, E); Dump_Result_List (File, E); end; Put_Line (File, " </FailedTests>"); Put_Line (File, "</TestRun>"); end Report; ------------------ -- Report_Error -- ------------------ procedure Report_Test (File : in Ada.Text_IO.File_Type; Test : in Test_Result) is use Util.Strings.Transforms; use type Ada.Calendar.Time; Is_Assert : Boolean; begin Put (File, " <Test"); if Test.Elapsed /= AUnit.Time_Measure.Null_Time then Put (File, " elapsed='"); Put (File, Test.Elapsed); Put_Line (File, "'>"); else Put_Line (File, ">"); end if; Put (File, " <Name>"); Put (File, Escape_Xml (Test.Test_Name.all)); if Test.Routine_Name /= null then Put (File, " : "); Put (File, Escape_Xml (Test.Routine_Name.all)); end if; Put_Line (File, "</Name>"); if Test.Failure /= null or else Test.Error /= null then if Test.Failure /= null then Is_Assert := True; else Is_Assert := False; end if; Put (File, " <FailureType>"); if Is_Assert then Put (File, "Assertion"); else Put (File, "Error"); end if; Put_Line (File, "</FailureType>"); Put (File, " <Message>"); if Is_Assert then Put (File, Escape_Xml (Test.Failure.Message.all)); else Put (File, Test.Error.Exception_Name.all); end if; Put_Line (File, "</Message>"); if Is_Assert then Put_Line (File, " <Location>"); Put (File, " <File>"); Put (File, Escape_Xml (Test.Failure.Source_Name.all)); Put_Line (File, "</File>"); Put (File, " <Line>"); Put (File, Test.Failure.Line); Put_Line (File, "</Line>"); Put_Line (File, " </Location>"); else Put_Line (File, " <Exception>"); Put (File, " <Message>"); Put (File, Test.Error.Exception_Name.all); Put_Line (File, "</Message>"); if Test.Error.Exception_Message /= null then Put (File, " <Information>"); Put (File, Escape_Xml (Test.Error.Exception_Message.all)); Put_Line (File, "</Information>"); end if; if Test.Error.Traceback /= null then Put (File, " <Traceback>"); Put (File, Escape_Xml (Test.Error.Traceback.all)); Put_Line (File, "</Traceback>"); end if; Put_Line (File, " </Exception>"); end if; end if; Put_Line (File, " </Test>"); end Report_Test; end Util.Tests.Reporter;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- A U N I T . R E P O R T E R . X M L -- -- -- -- B o d y -- -- -- -- -- -- Copyright (C) 2000-2009, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT 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 distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- GNAT is maintained by AdaCore (http://www.adacore.com) -- -- -- ------------------------------------------------------------------------------ with Util.Strings; with Util.Strings.Transforms; with AUnit.Time_Measure; -- Very simple reporter to console package body Util.Tests.Reporter is use AUnit.Test_Results; use type AUnit.Message_String; use type AUnit.Time_Measure.Time; use Ada.Text_IO; procedure Print_Summary (R : in out Result'Class); procedure Dump_Result_List (File : in Ada.Text_IO.File_Type; L : in Result_Lists.List); -- List failed assertions -- procedure Put_Measure is new Gen_Put_Measure; -- Output elapsed time procedure Report_Test (File : in Ada.Text_IO.File_Type; Test : in Test_Result); -- Report a single assertion failure or unexpected exception procedure Put (File : in Ada.Text_IO.File_Type; I : in Integer); procedure Put (File : in Ada.Text_IO.File_Type; T : in AUnit.Time_Measure.Time); procedure Put (File : in Ada.Text_IO.File_Type; I : in Integer) is begin Ada.Text_IO.Put (File, Util.Strings.Image (I)); end Put; procedure Put (File : in Ada.Text_IO.File_Type; T : in AUnit.Time_Measure.Time) is use Ada.Calendar; D : constant Duration := T.Stop - T.Start; S : constant String := Duration'Image (D); Pos : Natural := S'Last; begin while Pos > S'First and S (Pos) = '0' loop Pos := Pos - 1; end loop; if D >= 0.0 then Put (File, S (S'First + 1 .. Pos)); else Put (File, S (S'First .. Pos)); end if; end Put; ---------------------- -- Dump_Result_List -- ---------------------- procedure Dump_Result_List (File : in Ada.Text_IO.File_Type; L : in Result_Lists.List) is use Result_Lists; C : Cursor := First (L); begin -- Note: can't use Iterate because it violates restriction -- No_Implicit_Dynamic_Code while Has_Element (C) loop Report_Test (File, Element (C)); Next (C); end loop; end Dump_Result_List; ------------ -- Report -- ------------ procedure Report (Engine : in XML_Reporter; R : in out Result'Class; Options : in AUnit.Options.AUnit_Options := AUnit.Options.Default_Options) is Output : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Output, Mode => Ada.Text_IO.Out_File, Name => To_String (Engine.File)); Engine.Report (Output, R); Ada.Text_IO.Close (Output); end Report; procedure Print_Summary (R : in out Result'Class) is S_Count : constant Integer := Integer (Success_Count (R)); F_Count : constant Integer := Integer (Failure_Count (R)); E_Count : constant Integer := Integer (Error_Count (R)); begin New_Line; Put ("Total Tests Run: "); Put (Util.Strings.Image (Integer (Test_Count (R)))); New_Line; Put ("Successful Tests: "); Put (Util.Strings.Image (S_Count)); New_Line; Put ("Failed Assertions: "); Put (Util.Strings.Image (F_Count)); New_Line; Put ("Unexpected Errors: "); Put (Util.Strings.Image (E_Count)); New_Line; end Print_Summary; ------------ -- Report -- ------------ procedure Report (Engine : XML_Reporter; File : in out Ada.Text_IO.File_Type; R : in out Result'Class) is pragma Unreferenced (Engine); begin Put_Line (File, "<?xml version='1.0' encoding='utf-8' ?>"); Put (File, "<TestRun"); if Elapsed (R) /= AUnit.Time_Measure.Null_Time then Put (File, " elapsed='"); Put (File, Elapsed (R)); Put_Line (File, "'>"); else Put_Line (File, ">"); end if; Print_Summary (R); Put_Line (File, " <Statistics>"); Put (File, " <Tests>"); Put (File, Integer (Test_Count (R))); Put_Line (File, "</Tests>"); Put (File, " <FailuresTotal>"); Put (File, Integer (Failure_Count (R)) + Integer (Error_Count (R))); Put_Line (File, "</FailuresTotal>"); Put (File, " <Failures>"); Put (File, Integer (Failure_Count (R))); Put_Line (File, "</Failures>"); Put (File, " <Errors>"); Put (File, Integer (Error_Count (R))); Put_Line (File, "</Errors>"); Put_Line (File, " </Statistics>"); declare S : Result_Lists.List; begin Put_Line (File, " <SuccessfulTests>"); Successes (R, S); Dump_Result_List (File, S); Put_Line (File, " </SuccessfulTests>"); end; Put_Line (File, " <FailedTests>"); declare F : Result_Lists.List; begin Failures (R, F); Dump_Result_List (File, F); end; declare E : Result_Lists.List; begin Errors (R, E); Dump_Result_List (File, E); end; Put_Line (File, " </FailedTests>"); Put_Line (File, "</TestRun>"); end Report; ------------------ -- Report_Error -- ------------------ procedure Report_Test (File : in Ada.Text_IO.File_Type; Test : in Test_Result) is use Util.Strings.Transforms; use type Ada.Calendar.Time; Is_Assert : Boolean; begin Put (File, " <Test"); if Test.Elapsed /= AUnit.Time_Measure.Null_Time then Put (File, " elapsed='"); Put (File, Test.Elapsed); Put_Line (File, "'>"); else Put_Line (File, ">"); end if; Put (File, " <Name>"); Put (File, Escape_Xml (Test.Test_Name.all)); if Test.Routine_Name /= null then Put (File, " : "); Put (File, Escape_Xml (Test.Routine_Name.all)); end if; Put_Line (File, "</Name>"); if Test.Failure /= null or else Test.Error /= null then if Test.Failure /= null then Is_Assert := True; else Is_Assert := False; end if; Put (File, " <FailureType>"); if Is_Assert then Put (File, "Assertion"); else Put (File, "Error"); end if; Put_Line (File, "</FailureType>"); Put (File, " <Message>"); if Is_Assert then Put (File, Escape_Xml (Test.Failure.Message.all)); else Put (File, Test.Error.Exception_Name.all); end if; Put_Line (File, "</Message>"); if Is_Assert then Put_Line (File, " <Location>"); Put (File, " <File>"); Put (File, Escape_Xml (Test.Failure.Source_Name.all)); Put_Line (File, "</File>"); Put (File, " <Line>"); Put (File, Test.Failure.Line); Put_Line (File, "</Line>"); Put_Line (File, " </Location>"); else Put_Line (File, " <Exception>"); Put (File, " <Message>"); Put (File, Test.Error.Exception_Name.all); Put_Line (File, "</Message>"); if Test.Error.Exception_Message /= null then Put (File, " <Information>"); Put (File, Escape_Xml (Test.Error.Exception_Message.all)); Put_Line (File, "</Information>"); end if; if Test.Error.Traceback /= null then Put (File, " <Traceback>"); Put (File, Escape_Xml (Test.Error.Traceback.all)); Put_Line (File, "</Traceback>"); end if; Put_Line (File, " </Exception>"); end if; end if; Put_Line (File, " </Test>"); end Report_Test; end Util.Tests.Reporter;
Fix compilation with AUnit 2014
Fix compilation with AUnit 2014
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
4675fa37c87ba8046057dd4057cd50a329d6e97a
1-base/lace/source/text/lace-text-cursor.adb
1-base/lace/source/text/lace-text-cursor.adb
with ada.Characters.latin_1, ada.Characters.handling, ada.Strings.fixed, ada.Strings.Maps.Constants; -- with ada.text_IO; use ada.Text_IO; package body lace.text.Cursor is use ada.Strings; Integer_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789"); Float_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789."); -------- -- Forge -- function First (of_Text : access constant Text.item) return Cursor.item is the_Cursor : constant Cursor.item := (of_Text.all'unchecked_Access, 1); begin return the_Cursor; end First; ------------- -- Attributes -- function at_End (Self : in Item) return Boolean is begin return Self.Current = 0; end at_End; function has_Element (Self : in Item) return Boolean is begin return not at_End (Self) and Self.Current <= Self.Target.Length; end has_Element; procedure advance (Self : in out Item; Delimiter : in String := " "; Repeat : in Natural := 0; skip_Delimiter : in Boolean := True; match_Case : in Boolean := True) is begin for Count in 1 .. Repeat + 1 loop declare use ada.Characters.handling; delimiter_Position : Natural; begin if match_Case then delimiter_Position := fixed.Index (Self.Target.Data (1 .. Self.Target.Length), Delimiter, From => Self.Current); else delimiter_Position := fixed.Index (to_Lower (Self.Target.Data (1 .. Self.Target.Length)), to_Lower (Delimiter), From => Self.Current); end if; if delimiter_Position = 0 then Self.Current := 0; return; else if skip_Delimiter then Self.Current := delimiter_Position + Delimiter'Length; elsif Count = Repeat + 1 then Self.Current := delimiter_Position; else Self.Current := delimiter_Position + Delimiter'Length - 1; end if; end if; end; end loop; exception when constraint_Error => raise at_end_Error; end advance; procedure skip_White (Self : in out Item) is begin while has_Element (Self) and then ( Self.Target.Data (Self.Current) = ' ' or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.LF or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.HT) loop Self.Current := Self.Current + 1; end loop; end skip_White; procedure skip_Line (Self : in out Item) is Line : String := next_Line (Self) with Unreferenced; begin null; end skip_Line; function next_Token (Self : in out Item; Delimiter : in Character := ' '; Trim : in Boolean := False) return String is begin return next_Token (Self, "" & Delimiter, Trim); end next_Token; function next_Token (Self : in out item; Delimiter : in String; match_Case : in Boolean := True; Trim : in Boolean := False) return String is use ada.Characters.handling; begin if at_End (Self) then raise at_end_Error; end if; declare use ada.Strings.fixed, ada.Strings.Maps.Constants; delimiter_Position : constant Natural := (if match_Case then Index (Self.Target.Data (Self.Current .. Self.Target.Length), Delimiter, from => Self.Current) else Index (Self.Target.Data (Self.Current .. Self.Target.Length), to_Lower (Delimiter), from => Self.Current, mapping => lower_case_Map)); begin -- put_Line ("delimiter_Position" & delimiter_Position'Image); if delimiter_Position = 0 then return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. Self.Target.Length), Both) else Self.Target.Data (Self.Current .. Self.Target.Length)) do Self.Current := 0; end return; end if; return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. delimiter_Position - 1), Both) else Self.Target.Data (Self.Current .. delimiter_Position - 1)) do Self.Current := delimiter_Position + Delimiter'Length; end return; end; end next_Token; function next_Line (Self : in out Item; Trim : in Boolean := False) return String is use ada.Characters; Token : constant String := next_Token (Self, Delimiter => latin_1.LF, Trim => Trim); Pad : constant String := Token; --(if Token (Token'Last) = latin_1.CR then Token (Token'First .. Token'Last - 1) -- else Token); begin if Trim then return fixed.Trim (Pad, Both); else return Pad; end if; end next_Line; procedure skip_Token (Self : in out Item; Delimiter : in String := " "; match_Case : in Boolean := True) is ignored_Token : String := Self.next_Token (Delimiter, match_Case); begin null; end skip_Token; function get_Integer (Self : in out Item) return Integer is use ada.Strings.fixed; Text : String (1 .. Self.Length); First : Positive; Last : Natural; begin Text := Self.Target.Data (Self.Current .. Self.Target.Length); find_Token (Text, integer_Numerals, Inside, First, Last); if Last = 0 then raise No_Data_Error; end if; Self.Current := Self.Current + Last; return Integer'Value (Text (First .. Last)); end get_Integer; function get_Integer (Self : in out Item) return long_Integer is use ada.Strings.fixed; Text : String (1 .. Self.Length); First : Positive; Last : Natural; begin Text := Self.Target.Data (Self.Current .. Self.Target.Length); find_Token (Text, integer_Numerals, Inside, First, Last); if Last = 0 then raise No_Data_Error; end if; Self.Current := Self.Current + Last; return long_Integer'Value (Text (First .. Last)); end get_Integer; function get_Real (Self : in out Item) return long_Float is use ada.Strings.fixed; Text : String (1 .. Self.Length); First : Positive; Last : Natural; begin Text := Self.Target.Data (Self.Current .. Self.Target.Length); find_Token (Text, float_Numerals, Inside, First, Last); if Last = 0 then raise No_Data_Error; end if; Self.Current := Self.Current + Last; return long_Float'Value (Text (First .. Last)); end get_Real; function Length (Self : in Item) return Natural is begin return Self.Target.Length - Self.Current + 1; end Length; function peek (Self : in Item; Length : in Natural := Remaining) return String is Last : constant Natural := (if Length = Natural'Last then Self.Target.Length else Self.Current + Length - 1); begin if at_End (Self) then return ""; end if; return Self.Target.Data (Self.Current .. Last); end peek; function peek_Line (Self : in Item) return String is C : Cursor.item := Self; begin return next_Line (C); end peek_Line; end lace.text.Cursor;
with ada.Characters.latin_1, ada.Characters.handling, ada.Strings.fixed, ada.Strings.Maps.Constants; -- with ada.text_IO; use ada.Text_IO; package body lace.text.Cursor is use ada.Strings; Integer_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789"); Float_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789."); -------- -- Forge -- function First (of_Text : access constant Text.item) return Cursor.item is the_Cursor : constant Cursor.item := (of_Text.all'unchecked_Access, 1); begin return the_Cursor; end First; ------------- -- Attributes -- function at_End (Self : in Item) return Boolean is begin return Self.Current = 0; end at_End; function has_Element (Self : in Item) return Boolean is begin return not at_End (Self) and Self.Current <= Self.Target.Length; end has_Element; procedure advance (Self : in out Item; Delimiter : in String := " "; Repeat : in Natural := 0; skip_Delimiter : in Boolean := True; match_Case : in Boolean := True) is begin for Count in 1 .. Repeat + 1 loop declare use ada.Characters.handling; delimiter_Position : Natural; begin if match_Case then delimiter_Position := fixed.Index (Self.Target.Data (1 .. Self.Target.Length), Delimiter, From => Self.Current); else delimiter_Position := fixed.Index (to_Lower (Self.Target.Data (1 .. Self.Target.Length)), to_Lower (Delimiter), From => Self.Current); end if; if delimiter_Position = 0 then Self.Current := 0; return; else if skip_Delimiter then Self.Current := delimiter_Position + Delimiter'Length; elsif Count = Repeat + 1 then Self.Current := delimiter_Position; else Self.Current := delimiter_Position + Delimiter'Length - 1; end if; end if; end; end loop; exception when constraint_Error => raise at_end_Error; end advance; procedure skip_White (Self : in out Item) is begin while has_Element (Self) and then ( Self.Target.Data (Self.Current) = ' ' or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.LF or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.HT) loop Self.Current := Self.Current + 1; end loop; end skip_White; procedure skip_Line (Self : in out Item) is Line : String := next_Line (Self) with Unreferenced; begin null; end skip_Line; function next_Token (Self : in out Item; Delimiter : in Character := ' '; Trim : in Boolean := False) return String is begin return next_Token (Self, "" & Delimiter, Trim); end next_Token; function next_Token (Self : in out item; Delimiter : in String; match_Case : in Boolean := True; Trim : in Boolean := False) return String is use ada.Characters.handling; begin if at_End (Self) then raise at_end_Error; end if; declare function get_String return String is use ada.Strings.fixed, ada.Strings.Maps.Constants; delimiter_Position : constant Natural := (if match_Case then Index (Self.Target.Data (Self.Current .. Self.Target.Length), Delimiter, from => Self.Current) else Index (Self.Target.Data (Self.Current .. Self.Target.Length), to_Lower (Delimiter), from => Self.Current, mapping => lower_case_Map)); begin if delimiter_Position = 0 then return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. Self.Target.Length), Both) else Self.Target.Data (Self.Current .. Self.Target.Length)) do Self.Current := 0; end return; end if; return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. delimiter_Position - 1), Both) else Self.Target.Data (Self.Current .. delimiter_Position - 1)) do Self.Current := delimiter_Position + Delimiter'Length; end return; end get_String; unslid_String : constant String := get_String; slid_String : constant String (1 .. unslid_String'Length) := unslid_String; begin return slid_String; end; end next_Token; function next_Line (Self : in out Item; Trim : in Boolean := False) return String is use ada.Characters; Token : constant String := next_Token (Self, Delimiter => latin_1.LF, Trim => Trim); Pad : constant String := Token; --(if Token (Token'Last) = latin_1.CR then Token (Token'First .. Token'Last - 1) -- else Token); begin if Trim then return fixed.Trim (Pad, Both); else return Pad; end if; end next_Line; procedure skip_Token (Self : in out Item; Delimiter : in String := " "; match_Case : in Boolean := True) is ignored_Token : String := Self.next_Token (Delimiter, match_Case); begin null; end skip_Token; function get_Integer (Self : in out Item) return Integer is use ada.Strings.fixed; Text : String (1 .. Self.Length); First : Positive; Last : Natural; begin Text := Self.Target.Data (Self.Current .. Self.Target.Length); find_Token (Text, integer_Numerals, Inside, First, Last); if Last = 0 then raise No_Data_Error; end if; Self.Current := Self.Current + Last; return Integer'Value (Text (First .. Last)); end get_Integer; function get_Integer (Self : in out Item) return long_Integer is use ada.Strings.fixed; Text : String (1 .. Self.Length); First : Positive; Last : Natural; begin Text := Self.Target.Data (Self.Current .. Self.Target.Length); find_Token (Text, integer_Numerals, Inside, First, Last); if Last = 0 then raise No_Data_Error; end if; Self.Current := Self.Current + Last; return long_Integer'Value (Text (First .. Last)); end get_Integer; function get_Real (Self : in out Item) return long_Float is use ada.Strings.fixed; Text : String (1 .. Self.Length); First : Positive; Last : Natural; begin Text := Self.Target.Data (Self.Current .. Self.Target.Length); find_Token (Text, float_Numerals, Inside, First, Last); if Last = 0 then raise No_Data_Error; end if; Self.Current := Self.Current + Last; return long_Float'Value (Text (First .. Last)); end get_Real; function Length (Self : in Item) return Natural is begin return Self.Target.Length - Self.Current + 1; end Length; function peek (Self : in Item; Length : in Natural := Remaining) return String is Last : Natural := (if Length = Remaining then Self.Target.Length else Self.Current + Length - 1); begin if at_End (Self) then return ""; end if; Last := Natural'Min (Last, Self.Target.Length); return Self.Target.Data (Self.Current .. Last); end peek; function peek_Line (Self : in Item) return String is C : Cursor.item := Self; begin return next_Line (C); end peek_Line; end lace.text.Cursor;
Fix bug in the 'peek' function.
lace.text.cursor: Fix bug in the 'peek' function.
Ada
isc
charlie5/lace,charlie5/lace,charlie5/lace
112121bdfaa2a9959c341cfbcb0a4cc4c8a0d9eb
mat/src/mat-expressions.adb
mat/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(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; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); 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 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 => Ada.Strings.Unbounded.To_Unbounded_String (Name), Inside => Kind); return Result; end Create_Inside; end MAT.Expressions;
Implement the Create_Inside operation
Implement the Create_Inside operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
41924d9027722304dd0e027c2c00e281688ff895
src/base/os-linux64/util-systems-types.ads
src/base/os-linux64/util-systems-types.ads
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Types is subtype dev_t is Long_Long_Integer; subtype ino_t is Long_Long_Integer; subtype off_t is Long_Long_Integer; subtype blksize_t is Long_Long_Integer; subtype blkcnt_t is Long_Long_Integer; subtype uid_t is Interfaces.C.unsigned; subtype gid_t is Interfaces.C.unsigned; subtype nlink_t is Long_Long_Integer; subtype mode_t is Interfaces.C.unsigned; S_IFMT : constant mode_t := 8#00170000#; S_IFDIR : constant mode_t := 8#00040000#; S_IFCHR : constant mode_t := 8#00020000#; S_IFBLK : constant mode_t := 8#00060000#; S_IFREG : constant mode_t := 8#00100000#; S_IFIFO : constant mode_t := 8#00010000#; S_IFLNK : constant mode_t := 8#00120000#; S_IFSOCK : constant mode_t := 8#00140000#; S_ISUID : constant mode_t := 8#00004000#; S_ISGID : constant mode_t := 8#00002000#; S_IREAD : constant mode_t := 8#00000400#; S_IWRITE : constant mode_t := 8#00000200#; S_IEXEC : constant mode_t := 8#00000100#; type File_Type is new Interfaces.C.int; subtype Time_Type is Long_Long_Integer; type Timespec is record tv_sec : Time_Type; tv_nsec : Long_Long_Integer; end record; pragma Convention (C_Pass_By_Copy, Timespec); type Seek_Mode is (SEEK_SET, SEEK_CUR, SEEK_END); for Seek_Mode use (SEEK_SET => 0, SEEK_CUR => 1, SEEK_END => 2); STAT_NAME : constant String := "stat"; FSTAT_NAME : constant String := "fstat"; type Stat_Type is record st_dev : dev_t; st_ino : ino_t; st_nlink : nlink_t; st_mode : mode_t; st_uid : uid_t; st_gid : gid_t; pad1_0 : Interfaces.C.unsigned; st_rdev : dev_t; st_size : off_t; st_blksize : blksize_t; st_blocks : blkcnt_t; st_atim : Timespec; st_mtim : Timespec; st_ctim : Timespec; pad5 : Interfaces.C.unsigned_long; pad6 : Interfaces.C.unsigned_long; pad7 : Interfaces.C.unsigned_long; end record; pragma Convention (C_Pass_By_Copy, Stat_Type); end Util.Systems.Types;
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Types is subtype dev_t is Long_Long_Integer; subtype ino_t is Long_Long_Integer; subtype off_t is Long_Long_Integer; subtype blksize_t is Long_Long_Integer; subtype blkcnt_t is Long_Long_Integer; subtype uid_t is Interfaces.C.unsigned; subtype gid_t is Interfaces.C.unsigned; subtype nlink_t is Long_Long_Integer; subtype mode_t is Interfaces.C.unsigned; S_IFMT : constant mode_t := 8#00170000#; S_IFDIR : constant mode_t := 8#00040000#; S_IFCHR : constant mode_t := 8#00020000#; S_IFBLK : constant mode_t := 8#00060000#; S_IFREG : constant mode_t := 8#00100000#; S_IFIFO : constant mode_t := 8#00010000#; S_IFLNK : constant mode_t := 8#00120000#; S_IFSOCK : constant mode_t := 8#00140000#; S_ISUID : constant mode_t := 8#00004000#; S_ISGID : constant mode_t := 8#00002000#; S_IREAD : constant mode_t := 8#00000400#; S_IWRITE : constant mode_t := 8#00000200#; S_IEXEC : constant mode_t := 8#00000100#; type File_Type is new Interfaces.C.int; subtype Time_Type is Long_Long_Integer; type Timespec is record tv_sec : Time_Type; tv_nsec : Long_Long_Integer; end record; pragma Convention (C_Pass_By_Copy, Timespec); type Seek_Mode is (SEEK_SET, SEEK_CUR, SEEK_END); for Seek_Mode use (SEEK_SET => 0, SEEK_CUR => 1, SEEK_END => 2); STAT_NAME : constant String := "stat"; FSTAT_NAME : constant String := "fstat"; LSTAT_NAME : constant String := "lstat"; type Stat_Type is record st_dev : dev_t; st_ino : ino_t; st_nlink : nlink_t; st_mode : mode_t; st_uid : uid_t; st_gid : gid_t; pad1_0 : Interfaces.C.unsigned; st_rdev : dev_t; st_size : off_t; st_blksize : blksize_t; st_blocks : blkcnt_t; st_atim : Timespec; st_mtim : Timespec; st_ctim : Timespec; pad5 : Interfaces.C.unsigned_long; pad6 : Interfaces.C.unsigned_long; pad7 : Interfaces.C.unsigned_long; end record; pragma Convention (C_Pass_By_Copy, Stat_Type); end Util.Systems.Types;
Add LSTAT_NAME for lstat(2)
Add LSTAT_NAME for lstat(2)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bb18248d7190de35e499068a241d634967257d49
awa/awaunit/awa-tests-helpers-users.adb
awa/awaunit/awa-tests-helpers-users.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- Simulate a user login in the given service context. procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Permission_Manager, Principal => Principal.all'Access); end Login; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- Simulate a user login in the given service context. procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); end Login; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
Fix compilation
Fix compilation
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
c6db88ad812581ce0dcb99268a069bb6b437cf20
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with Util.Events; with MAT.Memory.Events; with MAT.Readers; with Ada.Containers.Ordered_Maps; package MAT.Memory.Targets is type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- 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); type Size_Info_Type is record Count : Natural; end record; use type MAT.Types.Target_Size; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out Size_Info_Map); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with Util.Events; with MAT.Memory.Events; with MAT.Readers; with Ada.Containers.Ordered_Maps; package MAT.Memory.Targets is type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- 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); type Size_Info_Type is record Count : Natural; end record; use type MAT.Types.Target_Size; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out Size_Info_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out Size_Info_Map); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Fix the definition of Size_Information procedure
Fix the definition of Size_Information procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
61e19cf6f98fa90b7bf383e4594c81d527e89dc6
awa/plugins/awa-images/src/awa-images-services.ads
awa/plugins/awa-images/src/awa-images-services.ads
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Permissions; with ADO; with AWA.Modules; with EL.Expressions; with AWA.Storages.Models; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package AWA.Images.Services is package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create"); PARAM_THUMBNAIL_COMMAND : constant String := "thumbnail_command"; -- ------------------------------ -- Image Service -- ------------------------------ -- The <b>Image_Service</b> works closely with the storage service. It extracts the -- information of an image, creates the image thumbnail. type Image_Service is new AWA.Modules.Module_Manager with private; type Image_Service_Access is access all Image_Service'Class; -- Initializes the image service. overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class); procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : out Natural); -- Build a thumbnail for the image identified by the Id. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); private type Image_Service is new AWA.Modules.Module_Manager with record Thumbnail_Command : EL.Expressions.Expression; end record; end AWA.Images.Services;
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Permissions; with ADO; with AWA.Modules; with EL.Expressions; with AWA.Storages.Models; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package AWA.Images.Services is package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create"); PARAM_THUMBNAIL_COMMAND : constant String := "thumbnail_command"; -- ------------------------------ -- Image Service -- ------------------------------ -- The <b>Image_Service</b> works closely with the storage service. It extracts the -- information of an image, creates the image thumbnail. type Image_Service is new AWA.Modules.Module_Manager with private; type Image_Service_Access is access all Image_Service'Class; -- Initializes the image service. overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class); procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : in out Natural; Height : in out Natural); -- Build a thumbnail for the image identified by the Id. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); -- Scale the image dimension. procedure Scale (Width : in Natural; Height : in Natural; To_Width : in out Natural; To_Height : in out Natural); -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width, Height := 0 -- <width>x -> Width := <width>, Height := 0 -- x<height> -> Width := 0, Height := <height> -- <width>x<height> -> Width := <width>, Height := <height> procedure Get_Sizes (Dimension : in String; Width : out Natural; Height : out Natural); private type Image_Service is new AWA.Modules.Module_Manager with record Thumbnail_Command : EL.Expressions.Expression; end record; end AWA.Images.Services;
Declare Scale and Get_Size operation
Declare Scale and Get_Size operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3f633885788e4d41e47e5990eccc61c547caeb9d
regtests/util-streams-texts-tests.ads
regtests/util-streams-texts-tests.ads
----------------------------------------------------------------------- -- streams.texts.tests -- Unit tests for text streams -- Copyright (C) 2012, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Streams.Texts.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test reading a text stream. procedure Test_Read_Line (T : in out Test); -- Write on a text stream converting an integer and writing it. procedure Test_Write_Integer (T : in out Test); -- Write on a text stream converting an integer and writing it. procedure Test_Write_Long_Integer (T : in out Test); end Util.Streams.Texts.Tests;
----------------------------------------------------------------------- -- streams.texts.tests -- Unit tests for text streams -- Copyright (C) 2012, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Streams.Texts.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test reading a text stream. procedure Test_Read_Line (T : in out Test); -- Write on a text stream converting an integer and writing it. procedure Test_Write_Integer (T : in out Test); -- Write on a text stream converting an integer and writing it. procedure Test_Write_Long_Integer (T : in out Test); -- Write on a text stream. procedure Test_Write (T : in out Test); end Util.Streams.Texts.Tests;
Declare the Test_Write procedure
Declare the Test_Write procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
805a57f29a8220238ab4660f2a9793cf6567177a
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Blogs.Services; with AWA.Helpers.Requests; with AWA.Helpers.Selectors; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin if not From.Is_Null then return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id /= ADO.NO_IDENTIFIER then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin if not Bean.Post.Is_Inserted then Manager.Create_Post (Blog_Id => Bean.Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_Uri, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status, Result => Result); else Manager.Update_Post (Post_Id => Bean.Post.Get_Id, Title => Bean.Post.Get_Title, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; -- ------------------------------ -- Delete a post. -- ------------------------------ procedure Delete_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; begin Manager.Delete_Post (Post_Id => Bean.Post.Get_Id); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Delete_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); package Delete_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Delete_Post, Name => "delete"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access, 3 => Delete_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif From.Post.Is_Null then return Util.Beans.Objects.Null_Object; elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); elsif Name = POST_USERNAME_ATTR then return Util.Beans.Objects.To_Object (String '(From.Post.Get_Author.Get_Name)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR and not Util.Beans.Objects.Is_Empty (Value) then From.Load_Post (ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_STATUS_ATTR then From.Post.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value)); end if; end Set_Value; -- ------------------------------ -- Load the post. -- ------------------------------ procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Post.Module.Get_Session; begin Post.Post.Load (Session, Id); Post.Title := Post.Post.Get_Title; Post.Text := Post.Post.Get_Text; Post.URI := Post.Post.Get_Uri; -- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of -- objects does not work yet. Force loading the user here while the above -- session is still open. declare A : constant String := String '(Post.Post.Get_Author.Get_Name); pragma Unreferenced (A); begin null; end; end Load_Post; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Post_Bean_Access := new Post_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; function Create_From_Status is new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type, "blog_status_"); -- ------------------------------ -- Get a select item list which contains a list of post status. -- ------------------------------ function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Helpers; begin return Selectors.Create_Selector_Bean (Bundle => "blogs", Context => null, Create => Create_From_Status'Access).all'Access; end Create_Status_List; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Blogs.Services; with AWA.Helpers.Requests; with AWA.Helpers.Selectors; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Applications.Messages.Factory; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin if not From.Is_Null then return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id /= ADO.NO_IDENTIFIER then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Create or save the post. -- ------------------------------ procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin if not Bean.Is_Inserted then Manager.Create_Post (Blog_Id => Bean.Blog_Id, Title => Bean.Get_Title, URI => Bean.Get_Uri, Text => Bean.Get_Text, Status => Bean.Get_Status, Result => Result); else Manager.Update_Post (Post_Id => Bean.Get_Id, Title => Bean.Get_Title, Text => Bean.Get_Text, Status => Bean.Get_Status); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Save; -- ------------------------------ -- Delete a post. -- ------------------------------ procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; begin Manager.Delete_Post (Post_Id => Bean.Get_Id); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Delete; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Get_Id)); elsif Name = POST_USERNAME_ATTR then return Util.Beans.Objects.To_Object (String '(From.Get_Author.Get_Name)); else return AWA.Blogs.Models.Post_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR and not Util.Beans.Objects.Is_Empty (Value) then From.Load_Post (ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); elsif Name = POST_TEXT_ATTR then From.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_STATUS_ATTR then From.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value)); end if; end Set_Value; -- ------------------------------ -- Load the post. -- ------------------------------ procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Post.Module.Get_Session; begin Post.Load (Session, Id); -- Post.Title := Post.Post.Get_Title; -- Post.Text := Post.Post.Get_Text; -- Post.URI := Post.Post.Get_Uri; -- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of -- objects does not work yet. Force loading the user here while the above -- session is still open. declare A : constant String := String '(Post.Get_Author.Get_Name); pragma Unreferenced (A); begin null; end; end Load_Post; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Post_Bean_Access := new Post_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; function Create_From_Status is new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type, "blog_status_"); -- ------------------------------ -- Get a select item list which contains a list of post status. -- ------------------------------ function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Helpers; begin return Selectors.Create_Selector_Bean (Bundle => "blogs", Context => null, Create => Create_From_Status'Access).all'Access; end Create_Status_List; end AWA.Blogs.Beans;
Use the generated UML Ada beans - simplify the implementation - rename old operations according to UML model
Use the generated UML Ada beans - simplify the implementation - rename old operations according to UML model
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
f2d6bdebeda84613ccbda67ee53d107c89a26152
awa/plugins/awa-mail/src/awa-mail-modules.adb
awa/plugins/awa-mail/src/awa-mail-modules.adb
----------------------------------------------------------------------- -- awa-mail -- Mail module -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Mail.Beans; with AWA.Mail.Components.Factory; with AWA.Applications; with ASF.Servlets; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Log.Loggers; package body AWA.Mail.Modules is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Mail.Module"); package Register is new AWA.Modules.Beans (Module => Mail_Module, Module_Access => Mail_Module_Access); -- ------------------------------ -- Initialize the mail module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Mail_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the mail module"); -- Add the Mail UI components. App.Add_Components (AWA.Mail.Components.Factory.Definition); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Mail.Beans.Mail_Bean", Handler => AWA.Mail.Beans.Create_Mail_Bean'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 Mail_Module; Props : in ASF.Applications.Config) is Mailer : constant String := Props.Get ("mailer", "smtp"); begin Plugin.Mailer := AWA.Mail.Clients.Factory (Mailer, Props); end Configure; -- ------------------------------ -- Create a new mail message. -- ------------------------------ function Create_Message (Plugin : in Mail_Module) return AWA.Mail.Clients.Mail_Message_Access is begin return Plugin.Mailer.Create_Message; end Create_Message; -- ------------------------------ -- Get the mail template that must be used for the given event name. -- The mail template is configured by the property: <i>module</i>.template.<i>event</i>. -- ------------------------------ function Get_Template (Plugin : in Mail_Module; Name : in String) return String is Prop_Name : constant String := Plugin.Get_Name & ".template." & Name; begin return Plugin.Get_Config (Prop_Name); end Get_Template; -- ------------------------------ -- Receive an event sent by another module with <b>Send_Event</b> method. -- Format and send an email. -- ------------------------------ procedure Send_Mail (Plugin : in Mail_Module; Template : in String; Props : in Util.Beans.Objects.Maps.Map; Content : in AWA.Events.Module_Event'Class) is Name : constant String := Content.Get_Parameter ("name"); begin Log.Info ("Receive event {0} with template {1}", Name, Template); if Template = "" then Log.Debug ("No email template associated with event {0}", Name); return; end if; declare Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ptr : constant Util.Beans.Basic.Readonly_Bean_Access := Content'Unrestricted_Access; Bean : constant Util.Beans.Objects.Object := Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC); Dispatcher : constant ASF.Servlets.Request_Dispatcher := Plugin.Get_Application.Get_Request_Dispatcher (Template); begin Req.Set_Request_URI (Template); Req.Set_Method ("GET"); Req.Set_Attribute (Name => "event", Value => Bean); Req.Set_Attributes (Props); ASF.Servlets.Forward (Dispatcher, Req, Reply); end; end Send_Mail; -- ------------------------------ -- Get the mail module instance associated with the current application. -- ------------------------------ function Get_Mail_Module return Mail_Module_Access is function Get is new AWA.Modules.Get (Mail_Module, Mail_Module_Access, NAME); begin return Get; end Get_Mail_Module; end AWA.Mail.Modules;
----------------------------------------------------------------------- -- awa-mail -- Mail module -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Mail.Beans; with AWA.Mail.Components.Factory; with AWA.Applications; with ASF.Servlets; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Log.Loggers; package body AWA.Mail.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Module"); package Register is new AWA.Modules.Beans (Module => Mail_Module, Module_Access => Mail_Module_Access); -- ------------------------------ -- Initialize the mail module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Mail_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the mail module"); -- Add the Mail UI components. App.Add_Components (AWA.Mail.Components.Factory.Definition); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Mail.Beans.Mail_Bean", Handler => AWA.Mail.Beans.Create_Mail_Bean'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 Mail_Module; Props : in ASF.Applications.Config) is Mailer : constant String := Props.Get ("mailer", "smtp"); begin Log.Info ("Mail plugin is using {0} mailer", Mailer); Plugin.Mailer := AWA.Mail.Clients.Factory (Mailer, Props); end Configure; -- ------------------------------ -- Create a new mail message. -- ------------------------------ function Create_Message (Plugin : in Mail_Module) return AWA.Mail.Clients.Mail_Message_Access is begin return Plugin.Mailer.Create_Message; end Create_Message; -- ------------------------------ -- Get the mail template that must be used for the given event name. -- The mail template is configured by the property: <i>module</i>.template.<i>event</i>. -- ------------------------------ function Get_Template (Plugin : in Mail_Module; Name : in String) return String is Prop_Name : constant String := Plugin.Get_Name & ".template." & Name; begin return Plugin.Get_Config (Prop_Name); end Get_Template; -- ------------------------------ -- Receive an event sent by another module with <b>Send_Event</b> method. -- Format and send an email. -- ------------------------------ procedure Send_Mail (Plugin : in Mail_Module; Template : in String; Props : in Util.Beans.Objects.Maps.Map; Content : in AWA.Events.Module_Event'Class) is Name : constant String := Content.Get_Parameter ("name"); begin Log.Info ("Receive event {0} with template {1}", Name, Template); if Template = "" then Log.Debug ("No email template associated with event {0}", Name); return; end if; declare Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ptr : constant Util.Beans.Basic.Readonly_Bean_Access := Content'Unrestricted_Access; Bean : constant Util.Beans.Objects.Object := Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC); Dispatcher : constant ASF.Servlets.Request_Dispatcher := Plugin.Get_Application.Get_Request_Dispatcher (Template); begin Req.Set_Request_URI (Template); Req.Set_Method ("GET"); Req.Set_Attribute (Name => "event", Value => Bean); Req.Set_Attributes (Props); ASF.Servlets.Forward (Dispatcher, Req, Reply); end; end Send_Mail; -- ------------------------------ -- Get the mail module instance associated with the current application. -- ------------------------------ function Get_Mail_Module return Mail_Module_Access is function Get is new AWA.Modules.Get (Mail_Module, Mail_Module_Access, NAME); begin return Get; end Get_Mail_Module; end AWA.Mail.Modules;
Add a log message to report the mail plugin mailer configuration
Add a log message to report the mail plugin mailer configuration
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
87276c9e25441f1b72d1881bc9b657061b1471ed
src/asf-responses-mockup.adb
src/asf-responses-mockup.adb
----------------------------------------------------------------------- -- asf.responses -- ASF Requests -- 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. ----------------------------------------------------------------------- -- The <b>ASF.Responses</b> package is an Ada implementation of -- the Java servlet response (JSR 315 5. The Response). package body ASF.Responses.Mockup is -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Resp : in Response; Name : in String) return Boolean is Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name); begin return Util.Strings.Maps.Has_Element (Pos); end Contains_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Resp : in Response; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor); procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is begin Process.all (Name => Util.Strings.Maps.Key (Position), Value => Util.Strings.Maps.Element (Position)); end Process_Wrapper; begin Resp.Headers.Iterate (Process => Process_Wrapper'Access); end Iterate_Headers; -- ------------------------------ -- Sets a response header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ procedure Set_Header (Resp : in out Response; Name : in String; Value : in String) is begin Resp.Headers.Include (Name, Value); end Set_Header; -- ------------------------------ -- Adds a response header with the given name and value. -- This method allows response headers to have multiple values. -- ------------------------------ procedure Add_Header (Resp : in out Response; Name : in String; Value : in String) is begin Resp.Headers.Insert (Name, Value); end Add_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the response. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Resp : in Response; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else return ""; end if; end Get_Header; -- ------------------------------ -- Get the content written to the mockup output stream. -- ------------------------------ procedure Read_Content (Resp : in out Response; Into : out Ada.Strings.Unbounded.Unbounded_String) is begin Resp.Content.Read (Into => Into); end Read_Content; -- ------------------------------ -- Clear the response content. -- This operation removes any content held in the output stream, clears the status, -- removes any header in the response. -- ------------------------------ procedure Clear (Resp : in out Response) is Content : Ada.Strings.Unbounded.Unbounded_String; begin Resp.Read_Content (Content); Resp.Status := SC_OK; Resp.Headers.Clear; end Clear; -- ------------------------------ -- Initialize the response mockup output stream. -- ------------------------------ overriding procedure Initialize (Resp : in out Response) is begin Resp.Content.Initialize (128 * 1024); Resp.Stream := Resp.Content'Unchecked_Access; end Initialize; end ASF.Responses.Mockup;
----------------------------------------------------------------------- -- asf.responses -- ASF Requests -- 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. ----------------------------------------------------------------------- -- The <b>ASF.Responses</b> package is an Ada implementation of -- the Java servlet response (JSR 315 5. The Response). package body ASF.Responses.Mockup is -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Resp : in Response; Name : in String) return Boolean is Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name); begin return Util.Strings.Maps.Has_Element (Pos); end Contains_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Resp : in Response; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor); procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is begin Process.all (Name => Util.Strings.Maps.Key (Position), Value => Util.Strings.Maps.Element (Position)); end Process_Wrapper; begin Resp.Headers.Iterate (Process => Process_Wrapper'Access); end Iterate_Headers; -- ------------------------------ -- Sets a response header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ procedure Set_Header (Resp : in out Response; Name : in String; Value : in String) is begin Resp.Headers.Include (Name, Value); end Set_Header; -- ------------------------------ -- Adds a response header with the given name and value. -- This method allows response headers to have multiple values. -- ------------------------------ procedure Add_Header (Resp : in out Response; Name : in String; Value : in String) is begin if Resp.Headers.Contains (Name) then Resp.Headers.Include (Name, Resp.Headers.Element (Name) & ASCII.LF & Name & ": " & Value); else Resp.Headers.Insert (Name, Value); end if; end Add_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the response. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Resp : in Response; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else return ""; end if; end Get_Header; -- ------------------------------ -- Get the content written to the mockup output stream. -- ------------------------------ procedure Read_Content (Resp : in out Response; Into : out Ada.Strings.Unbounded.Unbounded_String) is begin Resp.Content.Read (Into => Into); end Read_Content; -- ------------------------------ -- Clear the response content. -- This operation removes any content held in the output stream, clears the status, -- removes any header in the response. -- ------------------------------ procedure Clear (Resp : in out Response) is Content : Ada.Strings.Unbounded.Unbounded_String; begin Resp.Read_Content (Content); Resp.Status := SC_OK; Resp.Headers.Clear; end Clear; -- ------------------------------ -- Initialize the response mockup output stream. -- ------------------------------ overriding procedure Initialize (Resp : in out Response) is begin Resp.Content.Initialize (128 * 1024); Resp.Stream := Resp.Content'Unchecked_Access; end Initialize; end ASF.Responses.Mockup;
Fix the response mockup to support several response headers with the same name
Fix the response mockup to support several response headers with the same name
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
b6d3603509394ddf176ba541ad56e09856718547
src/asf-servlets-mappers.adb
src/asf-servlets-mappers.adb
----------------------------------------------------------------------- -- asf-servlets-mappers -- Read servlet configuration files -- Copyright (C) 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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 0 .. Last - 1 loop N.URL_Patterns.Query_Element (Natural (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.Override_Context or else String '(N.Handler.all.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, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; 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 0 .. Last - 1 loop N.URL_Patterns.Query_Element (Natural (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.Override_Context or else String '(N.Handler.all.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 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 ("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 Reader_Config to use the new parser/mapper interface
Update the Reader_Config to use the new parser/mapper interface
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6bb688e8b2d0c6b61c9523dad8b87721304e6860
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "63"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "64"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
bump version to 1.64 belatedly
bump version to 1.64 belatedly
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
c86655dec3021ed872965851d00e125b63225b0b
src/wiki-parsers-common.ads
src/wiki-parsers-common.ads
----------------------------------------------------------------------- -- wiki-parsers-common -- Common operations with several wiki parsers -- Copyright (C) 2011 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private package Wiki.Parsers.Common is pragma Preelaborate; subtype Parser_Type is Parser; -- Check if this is a list item composed of '*' and '#' -- and terminated by a space. function Is_List (Text : in Wiki.Buffers.Buffer_Access; From : in Positive) return Boolean; procedure Skip_Spaces (Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Append (Into : in out Wiki.Strings.BString; Text : in Wiki.Buffers.Buffer_Access; From : in Positive); procedure Parse_Token (Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Escape_Char : in Wiki.Strings.WChar; Marker1 : in Wiki.Strings.WChar; Marker2 : in Wiki.Strings.WChar; Into : in out Wiki.Strings.BString); -- Parse a single text character and add it to the text buffer. procedure Parse_Text (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Count : in Positive := 1); procedure Parse_Paragraph (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_Horizontal_Rule (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar); -- Parse a preformatted header block. -- Example: -- /// -- ///html -- ///[Ada] -- {{{ -- ``` procedure Parse_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar); -- Parse a wiki heading. The heading could start with '=' or '!'. -- The trailing equals are ignored. -- Example: -- ==== Level 4 Creole -- == Level 2 == MediaWiki -- !!! Level 3 Dotclear procedure Parse_Header (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in Positive; Marker : in Wiki.Strings.WChar); -- Parse a template with parameters. -- Example: -- {{Name|param|...}} MediaWiki -- {{Name|param=value|...}} MediaWiki -- <<Name param=value ...>> Creole -- [{Name param=value ...}] JSPWiki procedure Parse_Template (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Token : in Wiki.Strings.WChar); procedure Parse_Entity (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a quote. -- Example: -- {{name}} -- {{name|language}} -- {{name|language|url}} -- ??citation?? procedure Parse_Quote (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar); procedure Parse_Html_Element (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Start : in Boolean); procedure Parse_Html_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a link. -- Example: -- [name] -- [name|url] -- [name|url|language] -- [name|url|language|title] -- [[link]] -- [[link|name]] procedure Parse_Link (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_List (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a list definition that starts with ';': -- ;item 1 -- : definition 1 procedure Parse_Definition (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); end Wiki.Parsers.Common;
----------------------------------------------------------------------- -- wiki-parsers-common -- Common operations with several wiki parsers -- Copyright (C) 2011 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private package Wiki.Parsers.Common is pragma Preelaborate; subtype Parser_Type is Parser; -- Check if this is a list item composed of '*' and '#' -- and terminated by a space. function Is_List (Text : in Wiki.Buffers.Buffer_Access; From : in Positive) return Boolean; procedure Skip_Spaces (Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Append (Into : in out Wiki.Strings.BString; Text : in Wiki.Buffers.Buffer_Access; From : in Positive); procedure Parse_Token (Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Escape_Char : in Wiki.Strings.WChar; Marker1 : in Wiki.Strings.WChar; Marker2 : in Wiki.Strings.WChar; Into : in out Wiki.Strings.BString); -- Parse a single text character and add it to the text buffer. procedure Parse_Text (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Count : in Positive := 1); procedure Parse_Paragraph (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_Horizontal_Rule (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar); -- Parse a preformatted header block. -- Example: -- /// -- ///html -- ///[Ada] -- {{{ -- ``` procedure Parse_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar); -- Parse a wiki heading. The heading could start with '=' or '!'. -- The trailing equals are ignored. -- Example: -- ==== Level 4 Creole -- == Level 2 == MediaWiki -- !!! Level 3 Dotclear procedure Parse_Header (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in Positive; Marker : in Wiki.Strings.WChar); -- Parse a template with parameters. -- Example: -- {{Name|param|...}} MediaWiki -- {{Name|param=value|...}} MediaWiki -- <<Name param=value ...>> Creole -- [{Name param=value ...}] JSPWiki procedure Parse_Template (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Token : in Wiki.Strings.WChar); procedure Parse_Entity (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Status : out Wiki.Html_Parser.Entity_State_Type; Entity : out Wiki.Strings.WChar); procedure Parse_Entity (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a quote. -- Example: -- {{name}} -- {{name|language}} -- {{name|language|url}} -- ??citation?? procedure Parse_Quote (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar); procedure Parse_Html_Element (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Start : in Boolean); procedure Parse_Html_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a link. -- Example: -- [name] -- [name|url] -- [name|url|language] -- [name|url|language|title] -- [[link]] -- [[link|name]] procedure Parse_Link (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_List (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a list definition that starts with ';': -- ;item 1 -- : definition 1 procedure Parse_Definition (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); end Wiki.Parsers.Common;
Add a Parse_Entity for the Markdown parser
Add a Parse_Entity for the Markdown parser
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
e919ebdf52aa9cd232376e092183586b54e65b61
samples/bean.adb
samples/bean.adb
----------------------------------------------------------------------- -- bean - A simple bean example -- 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. ----------------------------------------------------------------------- package body Bean is use EL.Objects; FIRST_NAME : constant String := "firstName"; LAST_NAME : constant String := "lastName"; AGE : constant String := "age"; Null_Object : Object; function Create_Person (First_Name, Last_Name : String; Age : Natural) return Person_Access is begin return new Person '(First_Name => To_Unbounded_String (First_Name), Last_Name => To_Unbounded_String (Last_Name), Age => Age); end Create_Person; -- Get the value identified by the name. function Get_Value (From : Person; Name : String) return EL.Objects.Object is begin if Name = FIRST_NAME then return To_Object (From.First_Name); elsif Name = LAST_NAME then return To_Object (From.Last_Name); elsif Name = AGE then return To_Object (From.Age); else return Null_Object; end if; end Get_Value; -- Set the value identified by the name. procedure Set_Value (From : in out Person; Name : in String; Value : in EL.Objects.Object) is begin if Name = FIRST_NAME then From.First_Name := To_Unbounded_String (Value); elsif Name = LAST_NAME then From.Last_Name := To_Unbounded_String (Value); elsif Name = AGE then From.Age := Natural (To_Integer (Value)); end if; end Set_Value; -- Function to format a string function Format (Arg : EL.Objects.Object) return EL.Objects.Object is S : constant String := To_String (Arg); begin return To_Object ("[" & S & "]"); end Format; end Bean;
----------------------------------------------------------------------- -- bean - A simple bean example -- 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. ----------------------------------------------------------------------- package body Bean is use EL.Objects; FIRST_NAME : constant String := "firstName"; LAST_NAME : constant String := "lastName"; AGE : constant String := "age"; Null_Object : Object; function Create_Person (First_Name, Last_Name : String; Age : Natural) return Person_Access is begin return new Person '(First_Name => To_Unbounded_String (First_Name), Last_Name => To_Unbounded_String (Last_Name), Age => Age); end Create_Person; -- Get the value identified by the name. function Get_Value (From : Person; Name : String) return EL.Objects.Object is begin if Name = FIRST_NAME then return To_Object (From.First_Name); elsif Name = LAST_NAME then return To_Object (From.Last_Name); elsif Name = AGE then return To_Object (From.Age); else return Null_Object; end if; end Get_Value; -- Set the value identified by the name. procedure Set_Value (From : in out Person; Name : in String; Value : in EL.Objects.Object) is begin if Name = FIRST_NAME then From.First_Name := To_Unbounded_String (Value); elsif Name = LAST_NAME then From.Last_Name := To_Unbounded_String (Value); elsif Name = AGE then From.Age := Natural (To_Integer (Value)); end if; end Set_Value; -- Function to format a string function Format (Arg : EL.Objects.Object) return EL.Objects.Object is S : constant String := To_String (Arg); begin return To_Object ("[" & S & "]"); end Format; end Bean;
Fix indentation
Fix indentation
Ada
apache-2.0
stcarrez/ada-el
e5434e8864bce5dcc0b4f55a87dfbc53758c1180
src/drivers/ado-drivers.ads
src/drivers/ado-drivers.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 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.Properties; -- == Database Drivers == -- Database drivers provide operations to access the database. These operations are -- specific to the database type and the `ADO.Drivers` package among others provide -- an abstraction that allows to make the different databases look like they have almost -- the same interface. -- -- A database driver exists for SQLite, MySQL and PostgreSQL. The driver -- is either statically linked to the application or it can be loaded dynamically if it was -- built as a shared library. For a dynamic load, the driver shared library name must be -- prefixed by `libada_ado_`. For example, for a `mysql` driver, the shared -- library name is `libada_ado_mysql.so`. -- -- | Driver name | Database | -- | ----------- | --------- | -- | mysql | MySQL, MariaDB | -- | sqlite | SQLite | -- | postgresql | PostgreSQL | -- -- The database drivers are initialized automatically but in some cases, you may want -- to control some database driver configuration parameter. In that case, -- the initialization must be done only once before creating a session -- factory and getting a database connection. The initialization can be made using -- a property file which contains the configuration for the database drivers and -- the database connection properties. For such initialization, you will have to -- call one of the `Initialize` operation from the `ADO.Drivers` package. -- -- ADO.Drivers.Initialize ("db.properties"); -- -- The set of configuration properties can be set programatically and passed to the -- `Initialize` operation. -- -- Config : Util.Properties.Manager; -- ... -- Config.Set ("ado.database", "sqlite:///mydatabase.db"); -- Config.Set ("ado.queries.path", ".;db"); -- ADO.Drivers.Initialize (Config); -- -- Once initialized, a configuration property can be retrieved by using the `Get_Config` -- operation. -- -- URI : constant String := ADO.Drivers.Get_Config ("ado.database"); -- -- Dynamic loading of database drivers is disabled by default for security reasons and -- it can be enabled by setting the following property in the configuration file: -- -- ado.drivers.load=true -- -- Dynamic loading is triggered when a database connection string refers to a database -- driver which is not known. -- -- @include ado-mysql.ads -- @include ado-sqlite.ads -- @include ado-postgresql.ads package ADO.Drivers is -- Raised for all errors reported by the database. Database_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; -- Returns true if the global configuration property is set to true/on. function Is_On (Name : in String) return Boolean; private -- Initialize the drivers which are available. procedure Initialize; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 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.Properties; -- == Database Drivers == -- Database drivers provide operations to access the database. These operations are -- specific to the database type and the `ADO.Drivers` package among others provide -- an abstraction that allows to make the different databases look like they have almost -- the same interface. -- -- A database driver exists for SQLite, MySQL and PostgreSQL. The driver -- is either statically linked to the application or it can be loaded dynamically if it was -- built as a shared library. For a dynamic load, the driver shared library name must be -- prefixed by `libada_ado_`. For example, for a `mysql` driver, the shared -- library name is `libada_ado_mysql.so`. -- -- | Driver name | Database | -- | ----------- | --------- | -- | mysql | MySQL, MariaDB | -- | sqlite | SQLite | -- | postgresql | PostgreSQL | -- -- The database drivers are initialized automatically but in some cases, you may want -- to control some database driver configuration parameter. In that case, -- the initialization must be done only once before creating a session -- factory and getting a database connection. The initialization can be made using -- a property file which contains the configuration for the database drivers and -- the database connection properties. For such initialization, you will have to -- call one of the `Initialize` operation from the `ADO.Drivers` package. -- -- ADO.Drivers.Initialize ("db.properties"); -- -- The set of configuration properties can be set programatically and passed to the -- `Initialize` operation. -- -- Config : Util.Properties.Manager; -- ... -- Config.Set ("ado.database", "sqlite:///mydatabase.db"); -- Config.Set ("ado.queries.path", ".;db"); -- ADO.Drivers.Initialize (Config); -- -- Once initialized, a configuration property can be retrieved by using the `Get_Config` -- operation. -- -- URI : constant String := ADO.Drivers.Get_Config ("ado.database"); -- -- Dynamic loading of database drivers is disabled by default for security reasons and -- it can be enabled by setting the following property in the configuration file: -- -- ado.drivers.load=true -- -- Dynamic loading is triggered when a database connection string refers to a database -- driver which is not known. -- -- @include ado-mysql.ads -- @include ado-sqlite.ads -- @include ado-postgresql.ads package ADO.Drivers is -- Raised for all errors reported by the database. Database_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; -- Returns true if the global configuration property is set to true/on. function Is_On (Name : in String) return Boolean; -- Initialize the drivers which are available. procedure Initialize; end ADO.Drivers;
Make the Initialize procedure public
Make the Initialize procedure public
Ada
apache-2.0
stcarrez/ada-ado
a7ef48e7bfba88110b0859ca9391dd00c01f7d37
tests/natools-smaz_tests.adb
tests/natools-smaz_tests.adb
------------------------------------------------------------------------------ -- Copyright (c) 2015-2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Characters.Latin_1; with Ada.Streams; with Ada.Strings.Unbounded; with Natools.S_Expressions; with Natools.Smaz_256; with Natools.Smaz_64; with Natools.Smaz_Generic; with Natools.Smaz_Original; with Natools.Smaz_Test_Base_64_Hash; package body Natools.Smaz_Tests is generic with package Smaz is new Natools.Smaz_Generic (<>); with function Image (S : Ada.Streams.Stream_Element_Array) return String; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array); function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String; function Direct_Image (S : Ada.Streams.Stream_Element_Array) return String renames Natools.S_Expressions.To_String; function To_SEA (S : String) return Ada.Streams.Stream_Element_Array renames Natools.S_Expressions.To_Atom; ----------------------- -- Test Dictionaries -- ----------------------- LF : constant Character := Ada.Characters.Latin_1.LF; Dict_64 : constant Natools.Smaz_64.Dictionary := (Last_Code => 59, Values_Last => 119, Variable_Length_Verbatim => False, Max_Word_Length => 6, Offsets => (2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 20, 22, 24, 25, 26, 28, 30, 31, 32, 36, 38, 40, 42, 44, 45, 47, 49, 51, 53, 56, 60, 63, 65, 68, 70, 72, 74, 76, 80, 82, 84, 88, 90, 92, 94, 98, 101, 102, 103, 105, 111, 112, 114, 115, 118), Values => " ee stainruos l dt enescm pépd de lere ld" & "e" & LF & "on cqumede mentes aiquen teerou r sque , is m q" & "ueà v'tiweblogfanj." & LF & LF & "ch", Hash => Natools.Smaz_Test_Base_64_Hash.Hash'Access); ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; begin for I in S'Range loop Append (Result, Ada.Streams.Stream_Element'Image (S (I))); end loop; return To_String (Result); end Decimal_Image; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array) is use type Ada.Streams.Stream_Element_Array; use type Ada.Streams.Stream_Element_Offset; begin declare First_OK : Boolean := False; begin declare Buffer : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Decompressed); begin First_OK := True; if Buffer /= Compressed then Test.Fail ("Bad compression of """ & Decompressed & '"'); Test.Info ("Found: " & Image (Buffer)); Test.Info ("Expected:" & Image (Compressed)); declare Round : constant String := Smaz.Decompress (Dict, Buffer); begin if Round /= Decompressed then Test.Info ("Roundtrip failed, got: """ & Round & '"'); else Test.Info ("Roundtrip OK"); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info ("During compression of """ & Decompressed & '"'); end if; Test.Report_Exception (Error, NT.Fail); end; declare First_OK : Boolean := False; begin declare Buffer : constant String := Smaz.Decompress (Dict, Compressed); begin First_OK := True; if Buffer /= Decompressed then Test.Fail ("Bad decompression of " & Image (Compressed)); Test.Info ("Found: """ & Buffer & '"'); Test.Info ("Expected:""" & Decompressed & '"'); declare Round : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Buffer); begin if Round /= Compressed then Test.Info ("Roundtrip failed, got: " & Image (Round)); else Test.Info ("Roundtrip OK"); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info ("During compression of " & Image (Compressed)); end if; Test.Report_Exception (Error, NT.Fail); end; end Generic_Roundtrip_Test; procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_256, Decimal_Image); procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_64, Direct_Image); ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Report.Section ("Base 256"); All_Tests_256 (Report); Report.End_Section; Report.Section ("Base 64"); All_Tests_64 (Report); Report.End_Section; end All_Tests; ------------------------------ -- Test Suite for Each Base -- ------------------------------ procedure All_Tests_256 (Report : in out NT.Reporter'Class) is begin Test_Validity_256 (Report); Sample_Strings_256 (Report); end All_Tests_256; procedure All_Tests_64 (Report : in out NT.Reporter'Class) is begin Test_Validity_64 (Report); Sample_Strings_64 (Report); end All_Tests_64; ------------------------------- -- Individual Base-256 Tests -- ------------------------------- procedure Sample_Strings_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Smaz_Original.Dictionary, "This is a small string", (254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "foobar", (220, 6, 90, 79)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "the end", (1, 171, 61)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "not-a-g00d-Exampl333", (132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109, 112, 108, 51, 51, 51)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "Smaz is a simple compression library", (254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166, 107, 205, 8, 90, 130, 12, 83)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "Nothing is more difficult, and therefore more precious, " & "than to be able to decide", (254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3, 148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203, 143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "this is an example of what works very well with smaz", (155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254, 107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "1000 numbers 2000 will 10 20 30 compress very little", (255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48, 48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51, 48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ": : : :", (255, 6, 58, 32, 58, 32, 58, 32, 58)); exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_256; procedure Test_Validity_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Test dictionary validity"); begin if not Natools.Smaz_256.Is_Valid (Smaz_Original.Dictionary) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_256; ------------------------------ -- Individual Base-64 Tests -- ------------------------------ procedure Sample_Strings_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Dict_64, "Simple Test", To_SEA ("+TBGSVYA+UBQE")); -- <S>imp* <T>*t exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_64; procedure Test_Validity_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Test dictionary validity"); begin if not Natools.Smaz_64.Is_Valid (Dict_64) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_64; end Natools.Smaz_Tests;
------------------------------------------------------------------------------ -- Copyright (c) 2015-2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Characters.Latin_1; with Ada.Streams; with Ada.Strings.Unbounded; with Natools.S_Expressions; with Natools.Smaz_256; with Natools.Smaz_64; with Natools.Smaz_Generic; with Natools.Smaz_Original; with Natools.Smaz_Test_Base_64_Hash; package body Natools.Smaz_Tests is generic with package Smaz is new Natools.Smaz_Generic (<>); with function Image (S : Ada.Streams.Stream_Element_Array) return String; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array); function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String; function Direct_Image (S : Ada.Streams.Stream_Element_Array) return String renames Natools.S_Expressions.To_String; function To_SEA (S : String) return Ada.Streams.Stream_Element_Array renames Natools.S_Expressions.To_Atom; ----------------------- -- Test Dictionaries -- ----------------------- LF : constant Character := Ada.Characters.Latin_1.LF; Dict_64 : constant Natools.Smaz_64.Dictionary := (Last_Code => 59, Values_Last => 119, Variable_Length_Verbatim => False, Max_Word_Length => 6, Offsets => (2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 20, 22, 24, 25, 26, 28, 30, 31, 32, 36, 38, 40, 42, 44, 45, 47, 49, 51, 53, 56, 60, 63, 65, 68, 70, 72, 74, 76, 80, 82, 84, 88, 90, 92, 94, 98, 101, 102, 103, 105, 111, 112, 114, 115, 118), Values => " ee stainruos l dt enescm pépd de lere ld" & "e" & LF & "on cqumede mentes aiquen teerou r sque , is m q" & "ueà v'tiweblogfanj." & LF & LF & "ch", Hash => Natools.Smaz_Test_Base_64_Hash.Hash'Access); ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; begin for I in S'Range loop Append (Result, Ada.Streams.Stream_Element'Image (S (I))); end loop; return To_String (Result); end Decimal_Image; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array) is use type Ada.Streams.Stream_Element_Array; use type Ada.Streams.Stream_Element_Offset; begin declare First_OK : Boolean := False; begin declare Buffer : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Decompressed); begin First_OK := True; if Buffer /= Compressed then Test.Fail ("Bad compression of """ & Decompressed & '"'); Test.Info ("Found: " & Image (Buffer)); Test.Info ("Expected:" & Image (Compressed)); declare Round : constant String := Smaz.Decompress (Dict, Buffer); begin if Round /= Decompressed then Test.Info ("Roundtrip failed, got: """ & Round & '"'); else Test.Info ("Roundtrip OK"); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info ("During compression of """ & Decompressed & '"'); end if; Test.Report_Exception (Error, NT.Fail); end; declare First_OK : Boolean := False; begin declare Buffer : constant String := Smaz.Decompress (Dict, Compressed); begin First_OK := True; if Buffer /= Decompressed then Test.Fail ("Bad decompression of " & Image (Compressed)); Test.Info ("Found: """ & Buffer & '"'); Test.Info ("Expected:""" & Decompressed & '"'); declare Round : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Buffer); begin if Round /= Compressed then Test.Info ("Roundtrip failed, got: " & Image (Round)); else Test.Info ("Roundtrip OK"); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info ("During compression of " & Image (Compressed)); end if; Test.Report_Exception (Error, NT.Fail); end; end Generic_Roundtrip_Test; procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_256, Decimal_Image); procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_64, Direct_Image); ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Report.Section ("Base 256"); All_Tests_256 (Report); Report.End_Section; Report.Section ("Base 64"); All_Tests_64 (Report); Report.End_Section; end All_Tests; ------------------------------ -- Test Suite for Each Base -- ------------------------------ procedure All_Tests_256 (Report : in out NT.Reporter'Class) is begin Test_Validity_256 (Report); Sample_Strings_256 (Report); end All_Tests_256; procedure All_Tests_64 (Report : in out NT.Reporter'Class) is begin Test_Validity_64 (Report); Sample_Strings_64 (Report); end All_Tests_64; ------------------------------- -- Individual Base-256 Tests -- ------------------------------- procedure Sample_Strings_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Smaz_Original.Dictionary, "This is a small string", (254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "foobar", (220, 6, 90, 79)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "the end", (1, 171, 61)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "not-a-g00d-Exampl333", (132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109, 112, 108, 51, 51, 51)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "Smaz is a simple compression library", (254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166, 107, 205, 8, 90, 130, 12, 83)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "Nothing is more difficult, and therefore more precious, " & "than to be able to decide", (254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3, 148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203, 143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "this is an example of what works very well with smaz", (155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254, 107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "1000 numbers 2000 will 10 20 30 compress very little", (255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48, 48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51, 48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ": : : :", (255, 6, 58, 32, 58, 32, 58, 32, 58)); exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_256; procedure Test_Validity_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Test dictionary validity"); begin if not Natools.Smaz_256.Is_Valid (Smaz_Original.Dictionary) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_256; ------------------------------ -- Individual Base-64 Tests -- ------------------------------ procedure Sample_Strings_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Dict_64, "Simple Test", To_SEA ("+TBGSVYA+UBQE")); -- <S>imp* <T>*t Roundtrip_Test (Test, Dict_64, "SiT", To_SEA ("/ATlGV")); -- <SiT> smaller than <S>i<T> ("+TBG+UB") Roundtrip_Test (Test, Dict_64, "sIMple TEST_WITH_14_B", To_SEA ("D9J1EVYA8UVETR1XXlEVI9VM08lQ")); -- s<IM>p* <TE ST_ WIT H_1 4_B> -- TE 001010_10 1010_0010 00 -- ST_ 110010_10 0010_1010 11_111010 -- WIT 111010_10 1001_0010 00_101010 -- H_1 000100_10 1111_1010 10_001100 -- 4_B 001011_00 1111_1010 01_000010 Roundtrip_Test (Test, Dict_64, "'7B_Verbatim'", To_SEA ("0+3IC9lVlJnYF1S0")); -- '<7B_Verb >a*m' -- 7 111011_00 0100 -- B_V 010000_10 1111_1010 01_101010 -- erb 101001_10 0100_1110 01_000110 -- "erb" could have been encoded separately as "o+iB", which has -- the same length, but the tie is broken in favor of the longer -- verbatim fragment to help with corner cases. exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_64; procedure Test_Validity_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Test dictionary validity"); begin if not Natools.Smaz_64.Is_Valid (Dict_64) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_64; end Natools.Smaz_Tests;
add tests to fully cover non-variable-verbatim code
smaz_tests: add tests to fully cover non-variable-verbatim code
Ada
isc
faelys/natools
6fff73613b004783869c24ab7dee5768b8c4d767
mat/src/mat-readers-streams-sockets.ads
mat/src/mat-readers-streams-sockets.ads
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Streams.Sockets; with GNAT.Sockets; package MAT.Readers.Streams.Sockets is type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with private; -- Initialize the socket listener. overriding procedure Initialize (Listener : in out Socket_Listener_Type); -- Destroy the socket listener. overriding procedure Finalize (Listener : in out Socket_Listener_Type); -- Open the socket to accept connections and start the listener task. procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type); -- Stop the listener socket. procedure Stop (Listener : in out Socket_Listener_Type); type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private; type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class; -- Open the socket to accept connections. procedure Open (Reader : in out Socket_Reader_Type; Address : in GNAT.Sockets.Sock_Addr_Type); procedure Close (Reader : in out Socket_Reader_Type); private type Socket_Listener_Type_Access is access all Socket_Listener_Type; task type Socket_Listener_Task is entry Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); end Socket_Listener_Task; task type Socket_Reader_Task is entry Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); end Socket_Reader_Task; type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record Socket : aliased Util.Streams.Sockets.Socket_Stream; Server : Socket_Reader_Task; Stop : Boolean := False; end record; type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with record Accept_Selector : aliased GNAT.Sockets.Selector_Type; Listener : Socket_Listener_Task; end record; end MAT.Readers.Streams.Sockets;
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Streams.Sockets; with GNAT.Sockets; package MAT.Readers.Streams.Sockets is type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with private; -- Initialize the socket listener. overriding procedure Initialize (Listener : in out Socket_Listener_Type); -- Destroy the socket listener. overriding procedure Finalize (Listener : in out Socket_Listener_Type); -- Open the socket to accept connections and start the listener task. procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type); -- Stop the listener socket. procedure Stop (Listener : in out Socket_Listener_Type); -- Create a target instance for the new client. procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type); type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private; type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class; -- Open the socket to accept connections. procedure Open (Reader : in out Socket_Reader_Type; Address : in GNAT.Sockets.Sock_Addr_Type); procedure Close (Reader : in out Socket_Reader_Type); private type Socket_Listener_Type_Access is access all Socket_Listener_Type; task type Socket_Listener_Task is entry Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); end Socket_Listener_Task; task type Socket_Reader_Task is entry Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type); end Socket_Reader_Task; type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record Socket : aliased Util.Streams.Sockets.Socket_Stream; Server : Socket_Reader_Task; Stop : Boolean := False; end record; type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with record Accept_Selector : aliased GNAT.Sockets.Selector_Type; Listener : Socket_Listener_Task; end record; end MAT.Readers.Streams.Sockets;
Declare the Create_Target procedure to setup a new client reader
Declare the Create_Target procedure to setup a new client reader
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6e3088fd071a80585cc02ac7cc7fd6d0f3b575d3
regtests/util-commands-tests.adb
regtests/util-commands-tests.adb
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Util.Test_Caller; with Util.Commands.Parsers.GNAT_Parser; with Util.Commands.Drivers; package body Util.Commands.Tests is package Caller is new Util.Test_Caller (Test, "Commands"); type Test_Context_Type is record Number : Integer; Success : Boolean := False; end record; package Test_Command is new Util.Commands.Drivers (Context_Type => Test_Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => "test"); type Test_Command_Type is new Test_Command.Command_Type with record Opt_Count : aliased Integer := 0; Opt_V : aliased Boolean := False; Opt_N : aliased Boolean := False; Expect_V : Boolean := False; Expect_N : Boolean := False; Expect_C : Integer := 0; Expect_A : Integer := 0; Expect_Help : Boolean := False; end record; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Test_Context_Type); -- Write the help associated with the command. procedure Help (Command : in out Test_Command_Type; Context : in out Test_Context_Type); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute", Test_Execute'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help", Test_Help'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage", Test_Usage'Access); end Add_Tests; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type) is pragma Unreferenced (Name); begin Context.Success := Command.Opt_Count = Command.Expect_C and Command.Opt_V = Command.Expect_V and Command.Opt_N = Command.Expect_N and Args.Get_Count = Command.Expect_A and not Command.Expect_Help; end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Test_Context_Type) is begin GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-c:", Long_Switch => "--count=", Help => "Number option", Section => "", Initial => Integer (0), Default => Integer (10), Output => Command.Opt_Count'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-v", Long_Switch => "--verbose", Help => "Verbose option", Section => "", Output => Command.Opt_V'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-n", Long_Switch => "--not", Help => "Not option", Section => "", Output => Command.Opt_N'Access); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Test_Command_Type; Context : in out Test_Context_Type) is begin Context.Success := Command.Expect_Help; end Help; -- ------------------------------ -- Tests when the execution of commands. -- ------------------------------ procedure Test_Execute (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_V := True; C1.Expect_N := True; C1.Expect_C := 4; C1.Expect_A := 2; Initialize (Args, "list --count=4 -v -n test titi"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C1.Expect_V := False; C1.Expect_N := True; C1.Expect_C := 8; C1.Expect_A := 3; Initialize (Args, "list -c 8 -n test titi last"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Execute; -- ------------------------------ -- Test execution of help. -- ------------------------------ procedure Test_Help (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C2.Expect_Help := True; Initialize (Args, "help print"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Help; -- ------------------------------ -- Test usage operation. -- ------------------------------ procedure Test_Usage (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); Args.Initialize (Line => "cmd list"); declare Ctx : Test_Context_Type; begin D.Usage (Args, Ctx); C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Usage; end Util.Commands.Tests;
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Util.Test_Caller; with Util.Commands.Parsers.GNAT_Parser; with Util.Commands.Drivers; package body Util.Commands.Tests is package Caller is new Util.Test_Caller (Test, "Commands"); type Test_Context_Type is record Number : Integer; Success : Boolean := False; end record; package Test_Command is new Util.Commands.Drivers (Context_Type => Test_Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => "test"); type Test_Command_Type is new Test_Command.Command_Type with record Opt_Count : aliased Integer := 0; Opt_V : aliased Boolean := False; Opt_N : aliased Boolean := False; Expect_V : Boolean := False; Expect_N : Boolean := False; Expect_C : Integer := 0; Expect_A : Integer := 0; Expect_Help : Boolean := False; end record; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Test_Context_Type); -- Write the help associated with the command. procedure Help (Command : in out Test_Command_Type; Context : in out Test_Context_Type); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute", Test_Execute'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help", Test_Help'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage", Test_Usage'Access); end Add_Tests; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type) is pragma Unreferenced (Name); begin Context.Success := Command.Opt_Count = Command.Expect_C and Command.Opt_V = Command.Expect_V and Command.Opt_N = Command.Expect_N and Args.Get_Count = Command.Expect_A and not Command.Expect_Help; end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Test_Context_Type) is pragma Unreferenced (Context); begin GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-c:", Long_Switch => "--count=", Help => "Number option", Section => "", Initial => Integer (0), Default => Integer (10), Output => Command.Opt_Count'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-v", Long_Switch => "--verbose", Help => "Verbose option", Section => "", Output => Command.Opt_V'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-n", Long_Switch => "--not", Help => "Not option", Section => "", Output => Command.Opt_N'Access); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Test_Command_Type; Context : in out Test_Context_Type) is begin Context.Success := Command.Expect_Help; end Help; -- ------------------------------ -- Tests when the execution of commands. -- ------------------------------ procedure Test_Execute (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_V := True; C1.Expect_N := True; C1.Expect_C := 4; C1.Expect_A := 2; Initialize (Args, "list --count=4 -v -n test titi"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C1.Expect_V := False; C1.Expect_N := True; C1.Expect_C := 8; C1.Expect_A := 3; Initialize (Args, "list -c 8 -n test titi last"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Execute; -- ------------------------------ -- Test execution of help. -- ------------------------------ procedure Test_Help (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C2.Expect_Help := True; Initialize (Args, "help print"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Help; -- ------------------------------ -- Test usage operation. -- ------------------------------ procedure Test_Usage (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); Args.Initialize (Line => "cmd list"); declare Ctx : Test_Context_Type; begin D.Usage (Args, Ctx); C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Usage; end Util.Commands.Tests;
Fix compilation warning, unused Context parameter
Fix compilation warning, unused Context parameter
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b81ced7920fe3f18193c1e52c7727ce53e003366
awa/plugins/awa-storages/src/awa-storages-modules.ads
awa/plugins/awa-storages/src/awa-storages-modules.ads
----------------------------------------------------------------------- -- awa-storages-modules -- Storage management module -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with AWA.Modules; with AWA.Storages.Services; with AWA.Storages.Servlets; -- == Storage Module == -- The <tt>Storage_Module</tt> type represents the storage module. An instance of the storage -- module must be declared and registered when the application is created and initialized. -- The storage module is associated with the storage service which provides and implements -- the storage management operations. package AWA.Storages.Modules is NAME : constant String := "storages"; type Storage_Module is new AWA.Modules.Module with private; type Storage_Module_Access is access all Storage_Module'Class; -- Initialize the storage module. overriding procedure Initialize (Plugin : in out Storage_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the storage manager. function Get_Storage_Manager (Plugin : in Storage_Module) return Services.Storage_Service_Access; -- Create a storage manager. This operation can be overridden to provide another -- storage service implementation. function Create_Storage_Manager (Plugin : in Storage_Module) return Services.Storage_Service_Access; -- Get the storage module instance associated with the current application. function Get_Storage_Module return Storage_Module_Access; -- Get the storage manager instance associated with the current application. function Get_Storage_Manager return Services.Storage_Service_Access; private type Storage_Module is new AWA.Modules.Module with record Manager : Services.Storage_Service_Access := null; Storage_Servlet : aliased AWA.Storages.Servlets.Storage_Servlet; end record; end AWA.Storages.Modules;
----------------------------------------------------------------------- -- awa-storages-modules -- Storage management module -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with AWA.Modules; with AWA.Storages.Services; with AWA.Storages.Servlets; -- == Storage Module == -- The <tt>Storage_Module</tt> type represents the storage module. An instance of the storage -- module must be declared and registered when the application is created and initialized. -- The storage module is associated with the storage service which provides and implements -- the storage management operations. package AWA.Storages.Modules is NAME : constant String := "storages"; type Storage_Module is new AWA.Modules.Module with private; type Storage_Module_Access is access all Storage_Module'Class; -- Initialize the storage module. overriding procedure Initialize (Plugin : in out Storage_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the storage manager. function Get_Storage_Manager (Plugin : in Storage_Module) return Services.Storage_Service_Access; -- Create a storage manager. This operation can be overridden to provide another -- storage service implementation. function Create_Storage_Manager (Plugin : in Storage_Module) return Services.Storage_Service_Access; -- Get the storage module instance associated with the current application. function Get_Storage_Module return Storage_Module_Access; -- Get the storage manager instance associated with the current application. function Get_Storage_Manager return Services.Storage_Service_Access; private type Storage_Module is new AWA.Modules.Module with record Manager : Services.Storage_Service_Access := null; Storage_Servlet : aliased AWA.Storages.Servlets.Storage_Servlet; end record; end AWA.Storages.Modules;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2736432ede742df0f7db79a291a7b894cb4d028c
src/asf-servlets.ads
src/asf-servlets.ads
----------------------------------------------------------------------- -- asf.servlets -- ASF Servlets -- Copyright (C) 2010, 2011, 2012, 2013, 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 ASF.Requests; with ASF.Responses; with ASF.Sessions; with ASF.Sessions.Factory; with ASF.Routes; limited with ASF.Filters; with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Strings.Hash; with Ada.Calendar; with Ada.Exceptions; with Util.Log; with Util.Properties; with Util.Strings.Vectors; with EL.Contexts; private with Ada.Containers.Indefinite_Hashed_Maps; -- The <b>ASF.Servlets</b> package implements a subset of the -- Java Servlet Specification adapted for the Ada language. -- -- The rationale for this implementation is to provide a set of -- interfaces and ways of developing a Web application which -- benefit from the architecture expertise defined in Java applications. -- -- The <b>ASF.Servlets</b>, <b>ASF.Requests</b>, <b>ASF.Responses</b> -- and <b>ASF.Sessions</b> packages are independent of the web server -- which will be used (such as <b>AWS</b>, <b>Apache</b> or <b>Lighthttpd</b>). -- package ASF.Servlets is Servlet_Error : exception; -- Filter chain as defined by JSR 315 6. Filtering type Filter_Chain is limited private; type Filter_Config is private; type Filter_Access is access all ASF.Filters.Filter'Class; type Filter_List_Access is access all ASF.Filters.Filter_List; -- Causes the next filter in the chain to be invoked, or if the calling -- filter is the last filter in the chain, causes the resource at the end -- of the chain to be invoked. procedure Do_Filter (Chain : in out Filter_Chain; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Get the filter name. function Get_Filter_Name (Config : in Filter_Config) return String; -- Returns a String containing the value of the named context-wide initialization -- parameter, or the default value if the parameter does not exist. -- -- The filter parameter name is automatically prefixed by the filter name followed by '.'. function Get_Init_Parameter (Config : in Filter_Config; Name : in String; Default : in String := "") return String; function Get_Init_Parameter (Config : in Filter_Config; Name : in String; Default : in String := "") return Ada.Strings.Unbounded.Unbounded_String; -- type Servlet_Registry; type Servlet_Registry is new ASF.Sessions.Factory.Session_Factory with private; type Servlet_Registry_Access is access all Servlet_Registry'Class; -- Get the servlet context associated with the filter chain. function Get_Servlet_Context (Chain : in Filter_Chain) return Servlet_Registry_Access; -- Get the servlet context associated with the filter config. function Get_Servlet_Context (Config : in Filter_Config) return Servlet_Registry_Access; -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. -- -- JSR 315 - 2. The Servlet Interface type Servlet is tagged limited private; type Servlet_Access is access all Servlet'Class; -- Get the servlet name. function Get_Name (Server : in Servlet) return String; -- Get the servlet context associated with this servlet. function Get_Servlet_Context (Server : in Servlet) return Servlet_Registry_Access; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- not overriding procedure Initialize (Server : in out Servlet; Context : in Servlet_Registry'Class); -- Receives standard HTTP requests from the public service method and dispatches -- them to the Do_XXX methods defined in this class. This method is an HTTP-specific -- version of the Servlet.service(Request, Response) method. There's no need -- to override this method. procedure Service (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Returns the time the Request object was last modified, in milliseconds since -- midnight January 1, 1970 GMT. If the time is unknown, this method returns -- a negative number (the default). -- -- Servlets that support HTTP GET requests and can quickly determine their -- last modification time should override this method. This makes browser and -- proxy caches work more effectively, reducing the load on server and network -- resources. function Get_Last_Modified (Server : in Servlet; Request : in Requests.Request'Class) return Ada.Calendar.Time; -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" procedure Do_Get (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Receives an HTTP HEAD request from the protected service method and handles -- the request. The client sends a HEAD request when it wants to see only the -- headers of a response, such as Content-Type or Content-Length. The HTTP HEAD -- method counts the output bytes in the response to set the Content-Length header -- accurately. -- -- If you override this method, you can avoid computing the response body and just -- set the response headers directly to improve performance. Make sure that the -- Do_Head method you write is both safe and idempotent (that is, protects itself -- from being called multiple times for one HTTP HEAD request). -- -- If the HTTP HEAD request is incorrectly formatted, doHead returns an HTTP -- "Bad Request" message. procedure Do_Head (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a POST request. The HTTP POST method allows the client to send data of unlimited -- length to the Web server a single time and is useful when posting information -- such as credit card numbers. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. When using -- a PrintWriter object to return the response, set the content type before -- accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container to use -- a persistent connection to return its response to the client, improving -- performance. The content length is automatically set if the entire response -- fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- This method does not need to be either safe or idempotent. Operations -- requested through POST can have side effects for which the user can be held -- accountable, for example, updating stored data or buying items online. -- -- If the HTTP POST request is incorrectly formatted, doPost returns -- an HTTP "Bad Request" message. procedure Do_Post (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a PUT request. The PUT operation allows a client to place a file on the server -- and is similar to sending a file by FTP. -- -- When overriding this method, leave intact any content headers sent with -- the request (including Content-Length, Content-Type, Content-Transfer-Encoding, -- Content-Encoding, Content-Base, Content-Language, Content-Location, -- Content-MD5, and Content-Range). If your method cannot handle a content -- header, it must issue an error message (HTTP 501 - Not Implemented) and -- discard the request. For more information on HTTP 1.1, see RFC 2616 . -- -- This method does not need to be either safe or idempotent. Operations that -- Do_Put performs can have side effects for which the user can be held accountable. -- When using this method, it may be useful to save a copy of the affected URL -- in temporary storage. -- -- If the HTTP PUT request is incorrectly formatted, Do_Put returns -- an HTTP "Bad Request" message. procedure Do_Put (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a DELETE request. The DELETE operation allows a client to remove a document -- or Web page from the server. -- -- This method does not need to be either safe or idempotent. Operations requested -- through DELETE can have side effects for which users can be held accountable. -- When using this method, it may be useful to save a copy of the affected URL in -- temporary storage. -- -- If the HTTP DELETE request is incorrectly formatted, Do_Delete returns an HTTP -- "Bad Request" message. procedure Do_Delete (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle a -- OPTIONS request. The OPTIONS request determines which HTTP methods the server -- supports and returns an appropriate header. For example, if a servlet overrides -- Do_Get, this method returns the following header: -- -- Allow: GET, HEAD, TRACE, OPTIONS -- -- There's no need to override this method unless the servlet implements new -- HTTP methods, beyond those implemented by HTTP 1.1. procedure Do_Options (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a TRACE request. A TRACE returns the headers sent with the TRACE request to -- the client, so that they can be used in debugging. There's no need to override -- this method. procedure Do_Trace (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- JSR 315 9. Dispatching Requests type Request_Dispatcher is limited private; -- Forwards a request from a servlet to another resource -- (servlet, or HTML file) on the server. This method allows one servlet to do -- preliminary processing of a request and another resource to generate the response. -- -- For a Request_Dispatcher obtained via Get_Request_Dispatcher(), -- the ServletRequest object has its path elements and parameters adjusted -- to match the path of the target resource. -- -- forward should be called before the response has been committed to the -- client (before response body output has been flushed). If the response -- already has been committed, this method throws an IllegalStateException. -- Uncommitted output in the response buffer is automatically cleared before -- the forward. -- -- The request and response parameters must be either the same objects as were -- passed to the calling servlet's service method or be subclasses of the -- RequestWrapper or ResponseWrapper classes that wrap them. procedure Forward (Dispatcher : in Request_Dispatcher; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Includes the content of a resource (servlet, or, HTML file) in the response. -- In essence, this method enables programmatic server-side includes. -- -- The Response object has its path elements and parameters remain -- unchanged from the caller's. The included servlet cannot change the response -- status code or set headers; any attempt to make a change is ignored. -- -- The request and response parameters must be either the same objects as were -- passed to the calling servlet's service method or be subclasses of the -- RequestWrapper or ResponseWrapper classes that wrap them. procedure Include (Dispatcher : in Request_Dispatcher; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Returns the servlet that will be called when forwarding the request. function Get_Servlet (Dispatcher : in Request_Dispatcher) return Servlet_Access; -- Returns a Request_Dispatcher object that acts as a wrapper for the resource -- located at the given path. A Request_Dispatcher object can be used to forward -- a request to the resource or to include the resource in a response. -- The resource can be dynamic or static. function Get_Request_Dispatcher (Context : in Servlet_Registry; Path : in String) return Request_Dispatcher; -- Returns a Request_Dispatcher object that acts as a wrapper for the named servlet. -- -- Servlets may be given names via server administration or via a web application -- deployment descriptor. A servlet instance can determine its name using -- ServletConfig.getServletName(). function Get_Name_Dispatcher (Context : in Servlet_Registry; Name : in String) return Request_Dispatcher; -- Returns the context path of the web application. -- The context path is the portion of the request URI that is used to select the context -- of the request. The context path always comes first in a request URI. The path starts -- with a "/" character but does not end with a "/" character. For servlets in the default -- (root) context, this method returns "". function Get_Context_Path (Context : in Servlet_Registry) return String; -- Returns a String containing the value of the named context-wide initialization -- parameter, or null if the parameter does not exist. -- -- This method can make available configuration information useful to an entire -- "web application". For example, it can provide a webmaster's email address -- or the name of a system that holds critical data. function Get_Init_Parameter (Context : in Servlet_Registry; Name : in String; Default : in String := "") return String; function Get_Init_Parameter (Context : in Servlet_Registry; Name : in String; Default : in String := "") return Ada.Strings.Unbounded.Unbounded_String; -- Set the init parameter identified by <b>Name</b> to the value <b>Value</b>. procedure Set_Init_Parameter (Context : in out Servlet_Registry; Name : in String; Value : in String); -- Set the init parameters by copying the properties defined in <b>Params</b>. -- Existing parameters will be overriding by the new values. procedure Set_Init_Parameters (Context : in out Servlet_Registry; Params : in Util.Properties.Manager'Class); -- Get access to the init parameters. procedure Get_Init_Parameters (Context : in Servlet_Registry; Process : not null access procedure (Params : in Util.Properties.Manager'Class)); -- Returns the absolute path of the resource identified by the given relative path. -- The resource is searched in a list of directories configured by the application. -- The path must begin with a "/" and is interpreted as relative to the current -- context root. -- -- This method allows the servlet container to make a resource available to -- servlets from any source. -- -- This method returns an empty string if the resource could not be localized. function Get_Resource (Context : in Servlet_Registry; Path : in String) return String; -- Registers the given servlet instance with this ServletContext under -- the given servletName. -- -- If this ServletContext already contains a preliminary -- ServletRegistration for a servlet with the given servletName, -- it will be completed (by assigning the class name of the given -- servlet instance to it) and returned. procedure Add_Servlet (Registry : in out Servlet_Registry; Name : in String; Server : in Servlet_Access); -- Registers the given filter instance with this Servlet context. procedure Add_Filter (Registry : in out Servlet_Registry; Name : in String; Filter : in Filter_Access); procedure Add_Filter (Registry : in out Servlet_Registry; Target : in String; Name : in String); -- Add a filter mapping with the given pattern -- If the URL pattern is already mapped to a different servlet, -- no updates will be performed. procedure Add_Filter_Mapping (Registry : in out Servlet_Registry; Pattern : in String; Name : in String); -- Add a servlet mapping with the given pattern -- If the URL pattern is already mapped to a different servlet, -- no updates will be performed. procedure Add_Mapping (Registry : in out Servlet_Registry; Pattern : in String; Name : in String); -- Add a servlet mapping with the given pattern -- If the URL pattern is already mapped to a different servlet, -- no updates will be performed. procedure Add_Mapping (Registry : in out Servlet_Registry; Pattern : in String; Server : in Servlet_Access); -- Add a route associated with the given path pattern. The pattern is split into components. -- Some path components can be a fixed string (/home) and others can be variable. -- When a path component is variable, the value can be retrieved from the route context. -- Once the route path is created, the <tt>Process</tt> procedure is called with the route -- reference. procedure Add_Route (Registry : in out Servlet_Registry; Pattern : in String; ELContext : in EL.Contexts.ELContext'Class; Process : not null access procedure (Route : in out ASF.Routes.Route_Type_Ref)); -- Set the error page that will be used if a servlet returns an error. procedure Set_Error_Page (Server : in out Servlet_Registry; Error : in Integer; Page : in String); -- Send the error page content defined by the response status. procedure Send_Error_Page (Server : in Servlet_Registry; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Report an error when an exception occurred while processing the request. procedure Error (Registry : in Servlet_Registry; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class; Ex : in Ada.Exceptions.Exception_Occurrence); -- Register the application represented by <b>Registry</b> under the base URI defined -- by <b>URI</b>. This is called by the Web container when the application is registered. -- The default implementation keeps track of the base URI to implement the context path -- operation. procedure Register_Application (Registry : in out Servlet_Registry; URI : in String); -- Start the application. procedure Start (Registry : in out Servlet_Registry); -- Finalize the servlet registry releasing the internal mappings. overriding procedure Finalize (Registry : in out Servlet_Registry); -- Dump the routes and filter configuration in the log with the given log level. procedure Dump_Routes (Registry : in out Servlet_Registry; Level : in Util.Log.Level_Type); private use Ada.Strings.Unbounded; -- Find the servlet and filter mapping that must be used for the given URI. -- Search the mapping according to Ch 12/SRV 11. Mapping Requests to Servlets: -- o look for an exact match, -- o look for the longest match, -- o look for an extension -- o use the default servlet mapping -- function Find_Mapping (Registry : in Servlet_Registry; -- URI : in String) return Mapping_Access; type Filter_Chain is limited record Filter_Pos : Natural; Filters : Filter_List_Access; Servlet : Servlet_Access; end record; type Request_Dispatcher is limited record Context : aliased ASF.Routes.Route_Context_Type; Filters : Filter_List_Access; Servlet : Servlet_Access := null; Pos : Natural := 0; end record; type Servlet is new Ada.Finalization.Limited_Controlled with record Name : Unbounded_String; Context : Servlet_Registry_Access := null; end record; package Filter_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Filter_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); package Filter_List_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Filter_List_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); package Servlet_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Servlet_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); function Hash (N : Integer) return Ada.Containers.Hash_Type; package Error_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Integer, Element_Type => String, Hash => Hash, Equivalent_Keys => "="); type Servlet_Registry is new ASF.Sessions.Factory.Session_Factory with record Config : Util.Properties.Manager; Servlets : Servlet_Maps.Map; Filters : Filter_Maps.Map; Filter_Rules : Filter_List_Maps.Map; Filter_Patterns : Util.Strings.Vectors.Vector; Error_Pages : Error_Maps.Map; Context_Path : Unbounded_String; Routes : ASF.Routes.Router_Type; end record; -- Install the servlet filters after all the mappings have been registered. procedure Install_Filters (Registry : in out Servlet_Registry); type Filter_Config is record Name : Unbounded_String; Context : Servlet_Registry_Access := null; end record; end ASF.Servlets;
----------------------------------------------------------------------- -- asf.servlets -- ASF Servlets -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Servlet.Core; with Servlet.Requests; with Servlet.Responses; package ASF.Servlets is subtype Servlet_Access is Servlet.Core.Servlet_Access; subtype Servlet_Registry is Servlet.Core.Servlet_Registry; subtype Servlet_Registry_Access is Servlet.Core.Servlet_Registry_Access; subtype Request_Dispatcher is Servlet.Core.Request_Dispatcher; subtype Filter_Config is Servlet.Core.Filter_Config; subtype Filter_Chain is Servlet.Core.Filter_Chain; -- Get the servlet context associated with the filter chain. function Get_Servlet_Context (Chain : in Filter_Chain) return Servlet_Registry_Access renames Servlet.Core.Get_Servlet_Context; -- Causes the next filter in the chain to be invoked, or if the calling -- filter is the last filter in the chain, causes the resource at the end -- of the chain to be invoked. procedure Do_Filter (Chain : in out Filter_Chain; Request : in out Servlet.Requests.Request'Class; Response : in out Servlet.Responses.Response'Class) renames Servlet.Core.Do_Filter; function Get_Init_Parameter (Config : in Filter_Config; Name : in String; Default : in String := "") return String renames Servlet.Core.Get_Init_Parameter; function Get_Init_Parameter (Config : in Filter_Config; Name : in String; Default : in String := "") return Ada.Strings.Unbounded.Unbounded_String renames Servlet.Core.Get_Init_Parameter; function Get_Init_Parameter (Context : in Servlet_Registry; Name : in String; Default : in String := "") return String renames Servlet.Core.Get_Init_Parameter; function Get_Init_Parameter (Context : in Servlet_Registry; Name : in String; Default : in String := "") return Ada.Strings.Unbounded.Unbounded_String renames Servlet.Core.Get_Init_Parameter; end ASF.Servlets;
Package ASF.Servlets moved to Servlet.Core
Package ASF.Servlets moved to Servlet.Core
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6e52096994b539a2871bd9fd2831dc7da0f30822
src/miscellaneous/commontext.adb
src/miscellaneous/commontext.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Strings.Fixed; with Ada.Strings.UTF_Encoding.Strings; package body CommonText is package AS renames Ada.Strings; package UES renames Ada.Strings.UTF_Encoding.Strings; ----------- -- USS -- ----------- function USS (US : Text) return String is begin return SU.To_String (US); end USS; ----------- -- SUS -- ----------- function SUS (S : String) return Text is begin return SU.To_Unbounded_String (S); end SUS; ------------- -- UTF8S -- ------------- function UTF8S (S8 : UTF8) return String is begin return UES.Decode (S8); end UTF8S; ------------- -- SUTF8 -- ------------- function SUTF8 (S : String) return UTF8 is begin return UES.Encode (S); end SUTF8; ----------------- -- IsBlank #1 -- ----------------- function IsBlank (US : Text) return Boolean is begin return SU.Length (US) = 0; end IsBlank; ----------------- -- IsBlank #2 -- ----------------- function IsBlank (S : String) return Boolean is begin return S'Length = 0; end IsBlank; ------------------ -- equivalent -- ------------------ function equivalent (A, B : Text) return Boolean is use type Text; begin return A = B; end equivalent; ------------------ -- equivalent -- ------------------ function equivalent (A : Text; B : String) return Boolean is AS : constant String := USS (A); begin return AS = B; end equivalent; -------------- -- trim #1 -- -------------- function trim (US : Text) return Text is begin return SU.Trim (US, AS.Both); end trim; -------------- -- trim #2 -- -------------- function trim (S : String) return String is begin return AS.Fixed.Trim (S, AS.Both); end trim; --------------- -- int2str -- --------------- function int2str (A : Integer) return String is raw : constant String := A'Img; len : constant Natural := raw'Length; begin return raw (2 .. len); end int2str; ---------------- -- int2text -- ---------------- function int2text (A : Integer) return Text is begin return SUS (int2str (A)); end int2text; ---------------- -- bool2str -- ---------------- function bool2str (A : Boolean) return String is begin if A then return "true"; end if; return "false"; end bool2str; ----------------- -- bool2text -- ----------------- function bool2text (A : Boolean) return Text is begin return SUS (bool2str (A)); end bool2text; -------------------- -- contains #1 -- -------------------- function contains (S : String; fragment : String) return Boolean is begin return (AS.Fixed.Index (Source => S, Pattern => fragment) > 0); end contains; -------------------- -- contains #2 -- -------------------- function contains (US : Text; fragment : String) return Boolean is begin return (SU.Index (Source => US, Pattern => fragment) > 0); end contains; -------------- -- part_1 -- -------------- function part_1 (S : String; separator : String := "/") return String is slash : Integer := AS.Fixed.Index (S, separator); begin if slash = 0 then return S; end if; return S (S'First .. slash - 1); end part_1; -------------- -- part_2 -- -------------- function part_2 (S : String; separator : String := "/") return String is slash : Integer := AS.Fixed.Index (S, separator); begin if slash = 0 then return S; end if; return S (slash + separator'Length .. S'Last); end part_2; --------------- -- replace -- --------------- function replace (S : String; reject, shiny : Character) return String is rejectstr : constant String (1 .. 1) := (1 => reject); focus : constant Natural := AS.Fixed.Index (Source => S, Pattern => rejectstr); returnstr : String := S; begin if focus > 0 then returnstr (focus) := shiny; end if; return returnstr; end replace; --------------- -- zeropad -- --------------- function zeropad (N : Natural; places : Positive) return String is template : String (1 .. places) := (others => '0'); myimage : constant String := trim (N'Img); startpos : constant Integer := 1 + places - myimage'Length; begin if startpos < 1 then return myimage; else template (startpos .. places) := myimage; return template; end if; end zeropad; -------------- -- len #1 -- -------------- function len (US : Text) return Natural is begin return SU.Length (US); end len; -------------- -- len #2 -- -------------- function len (S : String) return Natural is begin return S'Length; end len; ------------------ -- count_char -- ------------------ function count_char (S : String; focus : Character) return Natural is result : Natural := 0; begin for x in S'Range loop if S (x) = focus then result := result + 1; end if; end loop; return result; end count_char; --------------------- -- redact_quotes -- --------------------- function redact_quotes (sql : String) return String is -- This block will mask anything between quotes (single or double) -- These are considered to be literal and not suitable for binding type seeking is (none, single, double); redacted : String := sql; seek_status : seeking := none; arrow : Positive := 1; begin if IsBlank (sql) then return ""; end if; loop case sql (arrow) is when ''' => case seek_status is when none => seek_status := single; redacted (arrow) := '#'; when single => seek_status := none; redacted (arrow) := '#'; when double => null; end case; when ASCII.Quotation => case seek_status is when none => seek_status := double; redacted (arrow) := '#'; when double => seek_status := none; redacted (arrow) := '#'; when single => null; end case; when others => null; end case; exit when arrow = sql'Length; arrow := arrow + 1; end loop; return redacted; end redact_quotes; ---------------- -- trim_sql -- ---------------- function trim_sql (sql : String) return String is pass1 : String := trim (sql); pass2 : String (1 .. pass1'Length) := pass1; begin if pass2 (pass2'Last) = ASCII.Semicolon then return pass2 (1 .. pass2'Length - 1); else return pass2; end if; end trim_sql; --------------------- -- count_queries -- --------------------- function count_queries (trimmed_sql : String) return Natural is mask : String := redact_quotes (trimmed_sql); begin return count_char (S => mask, focus => ASCII.Semicolon) + 1; end count_queries; ---------------- -- subquery -- ---------------- function subquery (trimmed_sql : String; index : Positive) return String is mask : String := redact_quotes (trimmed_sql); start : Natural := trimmed_sql'First; segment : Natural := 1; scanning : Boolean := (index = segment); begin for x in mask'Range loop if mask (x) = ASCII.Semicolon then if scanning then return trimmed_sql (start .. x - 1); else segment := segment + 1; start := x + 1; scanning := (index = segment); end if; end if; end loop; -- Here we're either scanning (return current segment) or we aren't, -- meaning the index was too high, so return nothing. (This should -- never happen because caller knows how many segments there are and -- thus would not request something impossible like this.) if scanning then return trimmed_sql (start .. trimmed_sql'Last); else return ""; end if; end subquery; end CommonText;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Strings.Fixed; with Ada.Strings.UTF_Encoding.Strings; package body CommonText is package AS renames Ada.Strings; package UES renames Ada.Strings.UTF_Encoding.Strings; ----------- -- USS -- ----------- function USS (US : Text) return String is begin return SU.To_String (US); end USS; ----------- -- SUS -- ----------- function SUS (S : String) return Text is begin return SU.To_Unbounded_String (S); end SUS; ------------- -- UTF8S -- ------------- function UTF8S (S8 : UTF8) return String is begin return UES.Decode (S8); end UTF8S; ------------- -- SUTF8 -- ------------- function SUTF8 (S : String) return UTF8 is begin return UES.Encode (S); end SUTF8; ----------------- -- IsBlank #1 -- ----------------- function IsBlank (US : Text) return Boolean is begin return SU.Length (US) = 0; end IsBlank; ----------------- -- IsBlank #2 -- ----------------- function IsBlank (S : String) return Boolean is begin return S'Length = 0; end IsBlank; ------------------ -- equivalent -- ------------------ function equivalent (A, B : Text) return Boolean is use type Text; begin return A = B; end equivalent; ------------------ -- equivalent -- ------------------ function equivalent (A : Text; B : String) return Boolean is AS : constant String := USS (A); begin return AS = B; end equivalent; -------------- -- trim #1 -- -------------- function trim (US : Text) return Text is begin return SU.Trim (US, AS.Both); end trim; -------------- -- trim #2 -- -------------- function trim (S : String) return String is begin return AS.Fixed.Trim (S, AS.Both); end trim; --------------- -- int2str -- --------------- function int2str (A : Integer) return String is raw : constant String := A'Img; len : constant Natural := raw'Length; begin return raw (2 .. len); end int2str; ---------------- -- int2text -- ---------------- function int2text (A : Integer) return Text is begin return SUS (int2str (A)); end int2text; ---------------- -- bool2str -- ---------------- function bool2str (A : Boolean) return String is begin if A then return "true"; end if; return "false"; end bool2str; ----------------- -- bool2text -- ----------------- function bool2text (A : Boolean) return Text is begin return SUS (bool2str (A)); end bool2text; -------------------- -- contains #1 -- -------------------- function contains (S : String; fragment : String) return Boolean is begin return (AS.Fixed.Index (Source => S, Pattern => fragment) > 0); end contains; -------------------- -- contains #2 -- -------------------- function contains (US : Text; fragment : String) return Boolean is begin return (SU.Index (Source => US, Pattern => fragment) > 0); end contains; -------------- -- part_1 -- -------------- function part_1 (S : String; separator : String := "/") return String is slash : Integer := AS.Fixed.Index (S, separator); begin if slash = 0 then return S; end if; return S (S'First .. slash - 1); end part_1; -------------- -- part_2 -- -------------- function part_2 (S : String; separator : String := "/") return String is slash : Integer := AS.Fixed.Index (S, separator); begin if slash = 0 then return S; end if; return S (slash + separator'Length .. S'Last); end part_2; --------------- -- replace -- --------------- function replace (S : String; reject, shiny : Character) return String is rejectstr : constant String (1 .. 1) := (1 => reject); focus : constant Natural := AS.Fixed.Index (Source => S, Pattern => rejectstr); returnstr : String := S; begin if focus > 0 then returnstr (focus) := shiny; end if; return returnstr; end replace; --------------- -- zeropad -- --------------- function zeropad (N : Natural; places : Positive) return String is template : String (1 .. places) := (others => '0'); myimage : constant String := trim (N'Img); startpos : constant Integer := 1 + places - myimage'Length; begin if startpos < 1 then return myimage; else template (startpos .. places) := myimage; return template; end if; end zeropad; -------------- -- len #1 -- -------------- function len (US : Text) return Natural is begin return SU.Length (US); end len; -------------- -- len #2 -- -------------- function len (S : String) return Natural is begin return S'Length; end len; ------------------ -- count_char -- ------------------ function count_char (S : String; focus : Character) return Natural is result : Natural := 0; begin for x in S'Range loop if S (x) = focus then result := result + 1; end if; end loop; return result; end count_char; --------------------- -- redact_quotes -- --------------------- function redact_quotes (sql : String) return String is -- This block will mask anything between quotes (single or double) -- These are considered to be literal and not suitable for binding type seeking is (none, single, double); redacted : String := sql; seek_status : seeking := none; arrow : Positive := 1; begin if IsBlank (sql) then return ""; end if; loop case sql (arrow) is when ''' => case seek_status is when none => seek_status := single; redacted (arrow) := '#'; when single => seek_status := none; redacted (arrow) := '#'; when double => null; end case; when ASCII.Quotation => case seek_status is when none => seek_status := double; redacted (arrow) := '#'; when double => seek_status := none; redacted (arrow) := '#'; when single => null; end case; when others => null; end case; exit when arrow = sql'Length; arrow := arrow + 1; end loop; return redacted; end redact_quotes; ---------------- -- trim_sql -- ---------------- function trim_sql (sql : String) return String is pass1 : String := trim (sql); pass2 : String (1 .. pass1'Length) := pass1; begin if pass2 (pass2'Last) = ASCII.Semicolon then return pass2 (1 .. pass2'Length - 1); else return pass2; end if; end trim_sql; --------------------- -- count_queries -- --------------------- function count_queries (trimmed_sql : String) return Natural is mask : String := redact_quotes (trimmed_sql); begin return count_char (S => mask, focus => ASCII.Semicolon) + 1; end count_queries; ---------------- -- subquery -- ---------------- function subquery (trimmed_sql : String; index : Positive) return String is mask : String := redact_quotes (trimmed_sql); start : Natural := trimmed_sql'First; segment : Natural := 1; scanning : Boolean := (index = segment); begin for x in mask'Range loop if mask (x) = ASCII.Semicolon then if scanning then return trimmed_sql (start .. x - 1); else segment := segment + 1; start := x + 1; scanning := (index = segment); end if; end if; end loop; -- Here we're either scanning (return current segment) or we aren't, -- meaning the index was too high, so return nothing. (This should -- never happen because caller knows how many segments there are and -- thus would not request something impossible like this.) if scanning then return trim (trimmed_sql (start .. trimmed_sql'Last)); else return ""; end if; end subquery; end CommonText;
Trim each subquery to remove whitespace
commontext: Trim each subquery to remove whitespace
Ada
isc
jrmarino/AdaBase
c74f45e395cfef0d817fa0f8659951fa5652043f
awa/plugins/awa-settings/src/awa-settings-modules.ads
awa/plugins/awa-settings/src/awa-settings-modules.ads
----------------------------------------------------------------------- -- awa-settings-modules -- Module awa-settings -- 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 ASF.Applications; with Ada.Strings.Unbounded; with AWA.Modules; -- == Integration == -- The <tt>Setting_Module</tt> manages the application and user settings. An instance of the -- the <tt>Setting_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 -- Setting_Module : aliased AWA.Settings.Modules.Setting_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Settings.Modules.NAME, -- URI => "settings", -- Module => App.Setting_Module'Access); -- -- == Model == -- [images/awa_settings_model.png] package AWA.Settings.Modules is -- The name under which the module is registered. NAME : constant String := "awa-settings"; -- The name of the HTTP session attribute that contains user settings. SESSION_ATTR_NAME : constant String := "AWA.Settings"; -- The settings manager controls the creation and update of user settings. -- It maintains a small LRU cache of user settings that have been loaded and -- used by the application. The settings manager is intended to be stored as -- an HTTP session attribute. type Setting_Manager is new AWA.Modules.Module_Manager with private; type Setting_Manager_Access is access all Setting_Manager'Class; -- 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); -- 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); -- Get the current setting manager for the current user. function Current return Setting_Manager_Access; -- ------------------------------ -- Module awa-settings -- ------------------------------ type Setting_Module is new AWA.Modules.Module with private; type Setting_Module_Access is access all Setting_Module'Class; -- Initialize the settings module. overriding procedure Initialize (Plugin : in out Setting_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the settings module. function Get_Setting_Module return Setting_Module_Access; private type Setting_Module is new AWA.Modules.Module with null record; type Setting_Data; type Setting_Data_Access is access all Setting_Data; type Setting_Data is limited record Next_Setting : Setting_Data_Access; Name : Ada.Strings.Unbounded.Unbounded_String; Value : Ada.Strings.Unbounded.Unbounded_String; end record; protected type Settings is procedure Get (Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String); procedure Set (Name : in String; Value : in String); procedure Clear; private First : Setting_Data_Access := null; end Settings; type Setting_Manager is new AWA.Modules.Module_Manager with record Data : Settings; end record; end AWA.Settings.Modules;
----------------------------------------------------------------------- -- awa-settings-modules -- Module awa-settings -- Copyright (C) 2013, 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 ASF.Applications; with Ada.Strings.Unbounded; with AWA.Modules; -- == Integration == -- The <tt>Setting_Module</tt> manages the application and user settings. An instance of the -- the <tt>Setting_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 -- Setting_Module : aliased AWA.Settings.Modules.Setting_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Settings.Modules.NAME, -- URI => "settings", -- Module => App.Setting_Module'Access); -- -- == Model == -- [images/awa_settings_model.png] package AWA.Settings.Modules is -- The name under which the module is registered. NAME : constant String := "settings"; -- The name of the HTTP session attribute that contains user settings. SESSION_ATTR_NAME : constant String := "AWA.Settings"; -- The settings manager controls the creation and update of user settings. -- It maintains a small LRU cache of user settings that have been loaded and -- used by the application. The settings manager is intended to be stored as -- an HTTP session attribute. type Setting_Manager is new AWA.Modules.Module_Manager with private; type Setting_Manager_Access is access all Setting_Manager'Class; -- 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); -- 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); -- Get the current setting manager for the current user. function Current return Setting_Manager_Access; -- ------------------------------ -- Module awa-settings -- ------------------------------ type Setting_Module is new AWA.Modules.Module with private; type Setting_Module_Access is access all Setting_Module'Class; -- Initialize the settings module. overriding procedure Initialize (Plugin : in out Setting_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the settings module. function Get_Setting_Module return Setting_Module_Access; private type Setting_Module is new AWA.Modules.Module with null record; type Setting_Data; type Setting_Data_Access is access all Setting_Data; type Setting_Data is limited record Next_Setting : Setting_Data_Access; Name : Ada.Strings.Unbounded.Unbounded_String; Value : Ada.Strings.Unbounded.Unbounded_String; end record; protected type Settings is procedure Get (Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String); procedure Set (Name : in String; Value : in String); procedure Clear; private First : Setting_Data_Access := null; end Settings; type Setting_Manager is new AWA.Modules.Module_Manager with record Data : Settings; end record; end AWA.Settings.Modules;
Rename the module NAME into 'settings'
Rename the module NAME into 'settings'
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ca7d3f74880073f407301c68c9615610ed7aaa75
src/gen-commands-info.adb
src/gen-commands-info.adb
----------------------------------------------------------------------- -- gen-commands-info -- Collect and give information about the project -- 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 Ada.Text_IO; with Ada.Directories; with Gen.Utils; with Gen.Utils.GNAT; with Gen.Model.Projects; with Util.Strings.Sets; with Util.Files; package body Gen.Commands.Info is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector); procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean); procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition); procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition); procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count); procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition); procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count; List : in Gen.Model.Projects.Project_Vectors.Vector); List : Gen.Utils.String_List.Vector; Names : Util.Strings.Sets.Set; procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector) is procedure Add_Model_Dir (Base_Dir : in String; Dir : in String); procedure Add_Model_Dir (Base_Dir : in String; Dir : in String) is Path : constant String := Util.Files.Compose (Base_Dir, Dir); begin if not Result.Contains (Path) and then Ada.Directories.Exists (Path) then Result.Append (Path); end if; end Add_Model_Dir; Iter : Gen.Utils.String_List.Cursor := List.First; begin while Gen.Utils.String_List.Has_Element (Iter) loop declare Path : constant String := Gen.Utils.String_List.Element (Iter); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin Add_Model_Dir (Dir, "db"); Add_Model_Dir (Dir, "db/regtests"); Add_Model_Dir (Dir, "db/samples"); end; Gen.Utils.String_List.Next (Iter); end loop; end Collect_Directories; procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean) is pragma Unreferenced (Name); begin Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (File); Done := False; end Print_Model_File; -- ------------------------------ -- Print the list of GNAT projects used by the main project. -- ------------------------------ procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is use Gen.Utils.GNAT; Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First; Info : Project_Info; begin if Project_Info_Vectors.Has_Element (Iter) then Ada.Text_IO.Put_Line ("GNAT project files:"); while Project_Info_Vectors.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Info := Project_Info_Vectors.Element (Iter); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path)); Project_Info_Vectors.Next (Iter); end loop; end if; end Print_GNAT_Projects; -- ------------------------------ -- Print the list of Dynamo modules -- ------------------------------ procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count; List : in Gen.Model.Projects.Project_Vectors.Vector) is use Gen.Model.Projects; use type Ada.Text_IO.Positive_Count; Iter : Project_Vectors.Cursor := List.First; Ref : Model.Projects.Project_Reference; begin while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name)); Ada.Text_IO.Set_Col (Indent + 30); if Ref.Project /= null then Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path)); else Ada.Text_IO.Put_Line ("?"); end if; Project_Vectors.Next (Iter); end loop; end Print_Project_List; -- ------------------------------ -- Print the list of Dynamo modules -- ------------------------------ procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count) is use Gen.Model.Projects; use type Ada.Text_IO.Positive_Count; Iter : Project_Vectors.Cursor := Project.Modules.First; Ref : Model.Projects.Project_Reference; begin if not Project.Modules.Is_Empty then Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put_Line ("Dynamo plugins:"); Print_Project_List (Indent, Project.Modules); Print_Project_List (Indent, Project.Dependencies); Iter := Project.Modules.First; while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then declare Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name); begin Ada.Text_IO.Set_Col (Indent); if Names.Contains (Name) then Ada.Text_IO.Put_Line ("!! " & Name); else Names.Insert (Name); Ada.Text_IO.Put_Line ("== " & Name); Print_Modules (Ref.Project.all, Indent + 4); Names.Delete (Name); end if; end; end if; Project_Vectors.Next (Iter); end loop; end if; end Print_Modules; -- ------------------------------ -- Print the list of Dynamo projects used by the main project. -- ------------------------------ procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First; begin if Gen.Utils.String_List.Has_Element (Iter) then Ada.Text_IO.Put_Line ("Dynamo project files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Gen.Utils.String_List.Next (Iter); end loop; end if; end Print_Dynamo_Projects; procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is begin Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project)); Print_Dynamo_Projects (Project); Print_Modules (Project, 1); declare Model_Dirs : Gen.Utils.String_List.Vector; begin Collect_Directories (List, Model_Dirs); declare Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First; begin Ada.Text_IO.Put_Line ("ADO model files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Util.Files.Iterate_Files_Path (Pattern => "*.xml", Path => Gen.Utils.String_List.Element (Iter), Process => Print_Model_File'Access); Gen.Utils.String_List.Next (Iter); end loop; end; end; end Print_Project; begin Generator.Read_Project ("dynamo.xml", True); Generator.Update_Project (Print_Project'Access); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); begin Ada.Text_IO.Put_Line ("info: Print information about the current project"); Ada.Text_IO.Put_Line ("Usage: info"); Ada.Text_IO.New_Line; end Help; end Gen.Commands.Info;
----------------------------------------------------------------------- -- gen-commands-info -- Collect and give information about the project -- 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.Text_IO; with Ada.Directories; with Gen.Utils; with Gen.Utils.GNAT; with Gen.Model.Projects; with Util.Strings.Sets; with Util.Files; package body Gen.Commands.Info is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector); procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean); procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition); procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition); procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count); procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition); procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count; List : in Gen.Model.Projects.Project_Vectors.Vector); List : Gen.Utils.String_List.Vector; Names : Util.Strings.Sets.Set; procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector) is procedure Add_Model_Dir (Base_Dir : in String; Dir : in String); procedure Add_Model_Dir (Base_Dir : in String; Dir : in String) is Path : constant String := Util.Files.Compose (Base_Dir, Dir); begin if not Result.Contains (Path) and then Ada.Directories.Exists (Path) then Result.Append (Path); end if; end Add_Model_Dir; Iter : Gen.Utils.String_List.Cursor := List.First; begin while Gen.Utils.String_List.Has_Element (Iter) loop declare Path : constant String := Gen.Utils.String_List.Element (Iter); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin Add_Model_Dir (Dir, "db"); Add_Model_Dir (Dir, "db/regtests"); Add_Model_Dir (Dir, "db/samples"); end; Gen.Utils.String_List.Next (Iter); end loop; end Collect_Directories; procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean) is pragma Unreferenced (Name); begin Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (File); Done := False; end Print_Model_File; -- ------------------------------ -- Print the list of GNAT projects used by the main project. -- ------------------------------ procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is use Gen.Utils.GNAT; Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First; Info : Project_Info; begin if Project_Info_Vectors.Has_Element (Iter) then Ada.Text_IO.Put_Line ("GNAT project files:"); while Project_Info_Vectors.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Info := Project_Info_Vectors.Element (Iter); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path)); Project_Info_Vectors.Next (Iter); end loop; end if; end Print_GNAT_Projects; -- ------------------------------ -- Print the list of Dynamo modules -- ------------------------------ procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count; List : in Gen.Model.Projects.Project_Vectors.Vector) is use Gen.Model.Projects; use type Ada.Text_IO.Positive_Count; Iter : Project_Vectors.Cursor := List.First; Ref : Model.Projects.Project_Reference; begin while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name)); Ada.Text_IO.Set_Col (Indent + 30); if Ref.Project /= null then Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path)); else Ada.Text_IO.Put_Line ("?"); end if; Project_Vectors.Next (Iter); end loop; end Print_Project_List; -- ------------------------------ -- Print the list of Dynamo modules -- ------------------------------ procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count) is use Gen.Model.Projects; use type Ada.Text_IO.Positive_Count; Iter : Project_Vectors.Cursor := Project.Modules.First; Ref : Model.Projects.Project_Reference; begin if not Project.Modules.Is_Empty then Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put_Line ("Dynamo plugins:"); Print_Project_List (Indent, Project.Modules); Print_Project_List (Indent, Project.Dependencies); Iter := Project.Modules.First; while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then declare Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name); begin Ada.Text_IO.Set_Col (Indent); if Names.Contains (Name) then Ada.Text_IO.Put_Line ("!! " & Name); else Names.Insert (Name); Ada.Text_IO.Put_Line ("== " & Name); Print_Modules (Ref.Project.all, Indent + 4); Names.Delete (Name); end if; end; end if; Project_Vectors.Next (Iter); end loop; end if; end Print_Modules; -- ------------------------------ -- Print the list of Dynamo projects used by the main project. -- ------------------------------ procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First; begin if Gen.Utils.String_List.Has_Element (Iter) then Ada.Text_IO.Put_Line ("Dynamo project files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Gen.Utils.String_List.Next (Iter); end loop; end if; end Print_Dynamo_Projects; procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is begin Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project)); Print_Dynamo_Projects (Project); Print_Modules (Project, 1); declare Model_Dirs : Gen.Utils.String_List.Vector; begin Collect_Directories (List, Model_Dirs); declare Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First; begin Ada.Text_IO.Put_Line ("ADO model files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Util.Files.Iterate_Files_Path (Pattern => "*.xml", Path => Gen.Utils.String_List.Element (Iter), Process => Print_Model_File'Access); Gen.Utils.String_List.Next (Iter); end loop; end; end; end Print_Project; begin Generator.Read_Project ("dynamo.xml", True); Generator.Update_Project (Print_Project'Access); 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); begin Ada.Text_IO.Put_Line ("info: Print information about the current project"); Ada.Text_IO.Put_Line ("Usage: info"); Ada.Text_IO.New_Line; end Help; end Gen.Commands.Info;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
60ac0425a2532685de731514896ef50cc5ad92c0
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; -- List of folders. Folder_List : aliased AWA.Storages.Models.Folder_Info_List_Bean; Folder_List_Bean : AWA.Storages.Models.Folder_Info_List_Bean_Access; -- List of files. Files_List : aliased AWA.Storages.Models.Storage_Info_List_Bean; Files_List_Bean : AWA.Storages.Models.Storage_Info_List_Bean_Access; Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Storage_List_Bean_Access is access all Storage_List_Bean'Class; -- Load the folder instance. procedure Load_Folder (Storage : in Storage_List_Bean); -- Load the list of folders. procedure Load_Folders (Storage : in Storage_List_Bean); -- Load the list of files associated with the current folder. procedure Load_Files (Storage : in Storage_List_Bean); overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the files and folder information. overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Folder_List_Bean bean instance. function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Storage_List_Bean bean instance. function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Storage Bean -- ------------------------------ -- Information about a document (excluding the document data itself). type Storage_Bean is new AWA.Storages.Models.Storage_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access; end record; type Storage_Bean_Access is access all Storage_Bean'Class; overriding procedure Load (Into : in out Storage_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Storage_Bean bean instance. function Create_Storage_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2016, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Storages.Models; with AWA.Storages.Modules; with ASF.Parts; with ADO; with Util.Beans.Objects; with Util.Beans.Basic; -- == Storage Beans == -- The <tt>Upload_Bean</tt> type is used to upload a file in the storage space. -- It expect that the folder already exists. -- -- The <tt>Folder_Bean</tt> type controls the creation of new folders. -- -- The <tt>Storage_List_Bean</tt> type gives the files associated with a given folder. package AWA.Storages.Beans is FOLDER_ID_PARAMETER : constant String := "folderId"; -- ------------------------------ -- Upload Bean -- ------------------------------ -- The <b>Upload_Bean</b> allows to upload a file in the storage space. type Upload_Bean is new AWA.Storages.Models.Upload_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; Folder_Id : ADO.Identifier; Error : Boolean := False; end record; type Upload_Bean_Access is access all Upload_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Save the uploaded file in the storage service. -- @method procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class); -- Upload the file. overriding procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the file. overriding procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Publish the file. overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Upload_Bean bean instance. function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Folder Bean -- ------------------------------ -- The <b>Folder_Bean</b> allows to create or update the folder name. type Folder_Bean is new AWA.Storages.Models.Storage_Folder_Ref and Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; end record; type Folder_Bean_Access is access all Folder_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the folder. procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Init_Flag is (INIT_FOLDER, INIT_FOLDER_LIST, INIT_FILE_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Storage List Bean -- ------------------------------ -- This bean represents a list of storage files for a given folder. type Storage_List_Bean is new AWA.Storages.Models.Storage_List_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; -- Current folder. Folder : aliased Folder_Bean; Folder_Bean : Folder_Bean_Access; -- List of folders. Folder_List : aliased AWA.Storages.Models.Folder_Info_List_Bean; Folder_List_Bean : AWA.Storages.Models.Folder_Info_List_Bean_Access; -- List of files. Files_List : aliased AWA.Storages.Models.Storage_Info_List_Bean; Files_List_Bean : AWA.Storages.Models.Storage_Info_List_Bean_Access; Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Storage_List_Bean_Access is access all Storage_List_Bean'Class; -- Load the folder instance. procedure Load_Folder (Storage : in Storage_List_Bean); -- Load the list of folders. procedure Load_Folders (Storage : in Storage_List_Bean); -- Load the list of files associated with the current folder. procedure Load_Files (Storage : in Storage_List_Bean); overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the files and folder information. overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Folder_List_Bean bean instance. function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Storage_List_Bean bean instance. function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Storage Bean -- ------------------------------ -- Information about a document (excluding the document data itself). type Storage_Bean is new AWA.Storages.Models.Storage_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access; end record; type Storage_Bean_Access is access all Storage_Bean'Class; overriding 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;
Declare Is_Browser_Visible function and Get_Value for the Storage_Bean type
Declare Is_Browser_Visible function and Get_Value for the Storage_Bean type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
31053dbc9818ba66f75ce5354aad99bcd920aadb
mat/src/mat-readers-streams-sockets.adb
mat/src/mat-readers-streams-sockets.adb
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.Listener.Start (Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; -- Address.Addr := GNAT.Sockets.Addresses (Get_Host_By_Name (S.Get_Host), 1); -- Address.Addr := GNAT.Sockets.Any_Inet_Addr; -- Address.Port := 4096; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); -- Address := GNAT.Sockets.Get_Socket_Name (Server); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Socket_Reader_Task; -- Open the socket to accept connections. procedure Open (Reader : in out Socket_Reader_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Reading server stream"); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.Socket'Unchecked_Access, Output => null); Reader.Server.Start (Reader'Unchecked_Access, Address); end Open; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Initialize the socket listener. -- ------------------------------ overriding procedure Initialize (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Create_Selector (Listener.Accept_Selector); end Initialize; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.Listener.Start (Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; -- Address.Addr := GNAT.Sockets.Addresses (Get_Host_By_Name (S.Get_Host), 1); -- Address.Addr := GNAT.Sockets.Any_Inet_Addr; -- Address.Port := 4096; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); -- Address := GNAT.Sockets.Get_Socket_Name (Server); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Socket_Reader_Task; -- Open the socket to accept connections. procedure Open (Reader : in out Socket_Reader_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Reading server stream"); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.Socket'Unchecked_Access, Output => null); Reader.Server.Start (Reader'Unchecked_Access, Address); end Open; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
Implement the Initialize procedure to create the accept selector
Implement the Initialize procedure to create the accept selector
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
2a35d5e2750c128ce4e6bef7c2c6152797b13f9a
samples/encodes.adb
samples/encodes.adb
----------------------------------------------------------------------- -- encodes -- Encodes strings -- 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.Text_IO; with Ada.Command_Line; with Util.Encoders; procedure Encodes is use Util.Encoders; Encode : Boolean := True; Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count <= 1 then Ada.Text_IO.Put_Line ("Usage: encodes {encoder} [-d|-e] string..."); Ada.Text_IO.Put_Line ("Encoders: " & Util.Encoders.BASE_64 & ", " & Util.Encoders.BASE_64_URL & ", " & Util.Encoders.BASE_16 & ", " & Util.Encoders.HASH_SHA1); return; end if; declare Name : constant String := Ada.Command_Line.Argument (1); C : constant Encoder := Util.Encoders.Create (Name); begin for I in 2 .. Count loop declare S : constant String := Ada.Command_Line.Argument (I); begin if S = "-d" then Encode := False; elsif S = "-e" then Encode := True; elsif Encode then Ada.Text_IO.Put_Line ("Encodes " & Name & ": " & C.Encode (S)); else Ada.Text_IO.Put_Line ("Decodes " & Name & ": " & C.Decode (S)); end if; end; end loop; end; end Encodes;
----------------------------------------------------------------------- -- encodes -- Encodes strings -- 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.Text_IO; with Ada.Command_Line; with Util.Encoders; procedure Encodes is use Util.Encoders; Encode : Boolean := True; Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count <= 1 then Ada.Text_IO.Put_Line ("Usage: encodes {encoder} [-d|-e] string..."); Ada.Text_IO.Put_Line ("Encoders: " & Util.Encoders.BASE_64 & ", " & Util.Encoders.BASE_64_URL & ", " & Util.Encoders.BASE_16 & ", " & Util.Encoders.HASH_SHA1); return; end if; declare Name : constant String := Ada.Command_Line.Argument (1); C : constant Encoder := Util.Encoders.Create (Name); D : constant Decoder := Util.Encoders.Create (Name); begin for I in 2 .. Count loop declare S : constant String := Ada.Command_Line.Argument (I); begin if S = "-d" then Encode := False; elsif S = "-e" then Encode := True; elsif Encode then Ada.Text_IO.Put_Line ("Encodes " & Name & ": " & C.Encode (S)); else null; Ada.Text_IO.Put_Line ("Decodes " & Name & ": " & D.Decode (S)); end if; end; end loop; end; end Encodes;
fix encodes.adb by creating/using a Decoder in place of using Decode() over an Encoder.
fix encodes.adb by creating/using a Decoder in place of using Decode() over an Encoder.
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
81f73183574e4c418d98da2e3452c8a1002e16d3
src/util-serialize-io.ads
src/util-serialize-io.ads
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Strings.Unbounded; with Ada.Calendar; with Util.Beans.Objects; with Util.Streams; with Util.Streams.Buffered; with Util.Serialize.Contexts; with Util.Serialize.Mappers; with Util.Log.Loggers; with Util.Stacks; package Util.Serialize.IO is Parse_Error : exception; -- ------------------------------ -- Output stream for serialization -- ------------------------------ -- The <b>Output_Stream</b> interface defines the abstract operations for -- the serialization framework to write objects on the stream according to -- a target format such as XML or JSON. type Output_Stream is limited interface and Util.Streams.Output_Stream; -- Start a document. procedure Start_Document (Stream : in out Output_Stream) is null; -- Finish a document. procedure End_Document (Stream : in out Output_Stream) is null; procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is null; procedure End_Entity (Stream : in out Output_Stream; Name : in String) is null; -- Write the attribute name/value pair. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); -- Write the entity value. procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is abstract; procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is abstract; procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Start_Array (Stream : in out Output_Stream; Name : in String) is null; procedure End_Array (Stream : in out Output_Stream; Name : in String) is null; type Parser is abstract new Util.Serialize.Contexts.Context with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is abstract; -- Read the file and parse it using the parser. procedure Parse (Handler : in out Parser; File : in String); -- Parse the content string. procedure Parse_String (Handler : in out Parser; Content : in String); -- Returns true if the <b>Parse</b> operation detected at least one error. function Has_Error (Handler : in Parser) return Boolean; -- Set the error logger to report messages while parsing and reading the input file. procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access); -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. procedure Start_Object (Handler : in out Parser; Name : in String); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. procedure Finish_Object (Handler : in out Parser; Name : in String); procedure Start_Array (Handler : in out Parser; Name : in String); procedure Finish_Array (Handler : in out Parser; Name : in String); -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. procedure Set_Member (Handler : in out Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. procedure Error (Handler : in out Parser; Message : in String); procedure Add_Mapping (Handler : in out Parser; Path : in String; Mapper : in Util.Serialize.Mappers.Mapper_Access); -- Dump the mapping tree on the logger using the INFO log level. procedure Dump (Handler : in Parser'Class; Logger : in Util.Log.Loggers.Logger'Class); private -- Implementation limitation: the max number of active mapping nodes MAX_NODES : constant Positive := 10; type Mapper_Access_Array is array (1 .. MAX_NODES) of Serialize.Mappers.Mapper_Access; procedure Push (Handler : in out Parser); -- Pop the context and restore the previous context when leaving an element procedure Pop (Handler : in out Parser); function Find_Mapper (Handler : in Parser; Name : in String) return Util.Serialize.Mappers.Mapper_Access; type Element_Context is record -- The object mapper being process. Object_Mapper : Util.Serialize.Mappers.Mapper_Access; -- The active mapping nodes. Active_Nodes : Mapper_Access_Array; end record; type Element_Context_Access is access all Element_Context; package Context_Stack is new Util.Stacks (Element_Type => Element_Context, Element_Type_Access => Element_Context_Access); type Parser is abstract new Util.Serialize.Contexts.Context with record Error_Flag : Boolean := False; Stack : Context_Stack.Stack; Mapping_Tree : aliased Mappers.Mapper; Current_Mapper : Util.Serialize.Mappers.Mapper_Access; -- The file name to use when reporting errors. File : Ada.Strings.Unbounded.Unbounded_String; -- The logger which is used to report error messages when parsing an input file. Error_Logger : Util.Log.Loggers.Logger_Access := null; end record; end Util.Serialize.IO;
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Util.Beans.Objects; with Util.Streams; with Util.Streams.Buffered; with Util.Serialize.Contexts; with Util.Serialize.Mappers; with Util.Log.Loggers; with Util.Stacks; package Util.Serialize.IO is Parse_Error : exception; -- ------------------------------ -- Output stream for serialization -- ------------------------------ -- The <b>Output_Stream</b> interface defines the abstract operations for -- the serialization framework to write objects on the stream according to -- a target format such as XML or JSON. type Output_Stream is limited interface and Util.Streams.Output_Stream; -- Start a document. procedure Start_Document (Stream : in out Output_Stream) is null; -- Finish a document. procedure End_Document (Stream : in out Output_Stream) is null; procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is null; procedure End_Entity (Stream : in out Output_Stream; Name : in String) is null; -- Write the attribute name/value pair. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); -- Write the entity value. procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is abstract; procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is abstract; procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Start_Array (Stream : in out Output_Stream; Name : in String) is null; procedure End_Array (Stream : in out Output_Stream; Name : in String) is null; type Parser is abstract new Util.Serialize.Contexts.Context with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is abstract; -- Read the file and parse it using the parser. procedure Parse (Handler : in out Parser; File : in String); -- Parse the content string. procedure Parse_String (Handler : in out Parser; Content : in String); -- Returns true if the <b>Parse</b> operation detected at least one error. function Has_Error (Handler : in Parser) return Boolean; -- Set the error logger to report messages while parsing and reading the input file. procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access); -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. procedure Start_Object (Handler : in out Parser; Name : in String); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. procedure Finish_Object (Handler : in out Parser; Name : in String); procedure Start_Array (Handler : in out Parser; Name : in String); procedure Finish_Array (Handler : in out Parser; Name : in String); -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. procedure Set_Member (Handler : in out Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. procedure Error (Handler : in out Parser; Message : in String); procedure Add_Mapping (Handler : in out Parser; Path : in String; Mapper : in Util.Serialize.Mappers.Mapper_Access); -- Dump the mapping tree on the logger using the INFO log level. procedure Dump (Handler : in Parser'Class; Logger : in Util.Log.Loggers.Logger'Class); private -- Implementation limitation: the max number of active mapping nodes MAX_NODES : constant Positive := 10; type Mapper_Access_Array is array (1 .. MAX_NODES) of Serialize.Mappers.Mapper_Access; procedure Push (Handler : in out Parser); -- Pop the context and restore the previous context when leaving an element procedure Pop (Handler : in out Parser); function Find_Mapper (Handler : in Parser; Name : in String) return Util.Serialize.Mappers.Mapper_Access; type Element_Context is record -- The object mapper being process. Object_Mapper : Util.Serialize.Mappers.Mapper_Access; -- The active mapping nodes. Active_Nodes : Mapper_Access_Array; end record; type Element_Context_Access is access all Element_Context; package Context_Stack is new Util.Stacks (Element_Type => Element_Context, Element_Type_Access => Element_Context_Access); type Parser is abstract new Util.Serialize.Contexts.Context with record Error_Flag : Boolean := False; Stack : Context_Stack.Stack; Mapping_Tree : aliased Mappers.Mapper; Current_Mapper : Util.Serialize.Mappers.Mapper_Access; -- The file name to use when reporting errors. File : Ada.Strings.Unbounded.Unbounded_String; -- The logger which is used to report error messages when parsing an input file. Error_Logger : Util.Log.Loggers.Logger_Access := null; end record; end Util.Serialize.IO;
Remove with clause Ada.Containers
Remove with clause Ada.Containers
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e2f7fa879fc0d0b1a0c1d583f364b8d1eefd76f9
src/wiki-parsers-html.adb
src/wiki-parsers-html.adb
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; package body Wiki.Parsers.Html is use Ada.Strings.Wide_Wide_Unbounded; -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Space (C : in Wide_Wide_Character) return Boolean; function Is_Letter (C : in Wide_Wide_Character) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String); function Is_Space (C : in Wide_Wide_Character) return Boolean is begin return C = ' ' or C = LF or C = CR; end Is_Space; function Is_Letter (C : in Wide_Wide_Character) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; procedure Skip_Spaces (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); if not Is_Space (C) then Put_Back (P, C); return; end if; end loop; end Skip_Spaces; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; begin Name := To_Unbounded_Wide_Wide_String (""); Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Ada.Strings.Wide_Wide_Unbounded.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; Token : Wide_Wide_Character; begin Value := To_Unbounded_Wide_Wide_String (""); Peek (P, Token); if Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is C : Wide_Wide_Character; Name : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Attributes.Append (P.Attributes, Name, Value); elsif Is_Space (C) and Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end loop; -- Peek (P, C); -- Add any pending attribute. if Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wide_Wide_Character; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is Name : Unbounded_Wide_Wide_String; C : Wide_Wide_Character; begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); End_Element (P, Name); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Name, P.Attributes); End_Element (P, Name); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Name, P.Attributes); end if; end Parse_Element; end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Space (C : in Wide_Wide_Character) return Boolean; function Is_Letter (C : in Wide_Wide_Character) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String); function Is_Space (C : in Wide_Wide_Character) return Boolean is begin return C = ' ' or C = LF or C = CR; end Is_Space; function Is_Letter (C : in Wide_Wide_Character) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; procedure Skip_Spaces (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); if not Is_Space (C) then Put_Back (P, C); return; end if; end loop; end Skip_Spaces; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; begin Name := To_Unbounded_Wide_Wide_String (""); Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Ada.Strings.Wide_Wide_Unbounded.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; Token : Wide_Wide_Character; begin Value := To_Unbounded_Wide_Wide_String (""); Peek (P, Token); if Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is C : Wide_Wide_Character; Name : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Attributes.Append (P.Attributes, Name, Value); elsif Is_Space (C) and Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end loop; -- Peek (P, C); -- Add any pending attribute. if Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wide_Wide_Character; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is Name : Unbounded_Wide_Wide_String; C : Wide_Wide_Character; begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); End_Element (P, Name); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Name, P.Attributes); End_Element (P, Name); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Name, P.Attributes); end if; end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wide_Wide_Character) is Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wide_Wide_Character; begin loop Peek (P, C); exit when C = ';'; if Len < Name'Last then Len := Len + 1; end if; Name (Len) := Ada.Characters.Conversions.To_Character (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; end Parse_Entity; end Wiki.Parsers.Html;
Implement the Parse_Entity procedure
Implement the Parse_Entity procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki