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
354db3c24747a18880a2e07081065ea361f3f1ed
regtests/ado-drivers-tests.ads
regtests/ado-drivers-tests.ads
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Initialize operation. procedure Test_Initialize (T : in out Test); -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure. procedure Test_Set_Connection (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); -- Test the Set_Server operation. procedure Test_Set_Connection_Server (T : in out Test); -- Test the Set_Port operation. procedure Test_Set_Connection_Port (T : in out Test); -- Test the Set_Database operation. procedure Test_Set_Connection_Database (T : in out Test); -- Test the connection operations on an empty connection. procedure Test_Empty_Connection (T : in out Test); end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Initialize operation. procedure Test_Initialize (T : in out Test); -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure. procedure Test_Set_Connection (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); -- Test the Set_Server operation. procedure Test_Set_Connection_Server (T : in out Test); -- Test the Set_Port operation. procedure Test_Set_Connection_Port (T : in out Test); -- Test the Set_Database operation. procedure Test_Set_Connection_Database (T : in out Test); -- Test the connection operations on an empty connection. procedure Test_Empty_Connection (T : in out Test); -- Test the connection operations on a closed connection. procedure Test_Closed_Connection (T : in out Test); end ADO.Drivers.Tests;
Declare Test_Closed_Connection procedure
Declare Test_Closed_Connection procedure
Ada
apache-2.0
stcarrez/ada-ado
16538b928894a55820254df2aed5a2f1f300c05d
awa/plugins/awa-setup/src/awa-setup-applications.ads
awa/plugins/awa-setup/src/awa-setup-applications.ads
----------------------------------------------------------------------- -- awa-setup-applications -- Setup and installation -- Copyright (C) 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 ASF.Applications.Main; with ASF.Servlets.Faces; with Servlet.Core.Files; with ASF.Requests; with ASF.Responses; with ASF.Server; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; with ADO.Drivers.Connections; -- == Setup Procedure Instantiation== -- The setup process is managed by the *Configure* generic procedure. The procedure must -- be instantiated with the application class type and the application initialize procedure. -- -- procedure Setup is -- new AWA.Setup.Applications.Configure (MyApp.Application'Class, -- MyApp.Application_Access, -- MyApp.Initialize); -- -- == Setup Operation == -- The *Setup* instantiated operation must then be called with the web container. -- The web container is started first and the *Setup* procedure gets as parameter the -- web container, the application instance to configure, the application name and -- the application context path. -- -- Setup (WS, App, "atlas", MyApp.CONTEXT_PATH) -- -- The operation will install the setup application to handle the setup actions. Through -- the setup actions, the installer will be able to: -- -- * Configure the database (MySQL or SQLite), -- * Configure the Google+ and Facebook OAuth authentication keys, -- * Configure the application name, -- * Configure the mail parameters to be able to send email. -- -- After the setup and configure is finished, the file <tt>.initialized</tt> is created in -- the application directory to indicate the application is configured. The next time the -- *Setup* operation is called, the installation process will be skipped. -- -- To run again the installation, remove manually the <tt>.initialized</tt> file. package AWA.Setup.Applications is Empty : constant Util.Beans.Objects.Object := Util.Beans.Objects.To_Object (String '("")); -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Redirect_Servlet is new Servlet.Core.Servlet with null record; overriding procedure Do_Get (Server : in Redirect_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- The configuration state starts in the <tt>CONFIGURING</tt> state and moves to the -- <tt>STARTING</tt> state after the application is configured and it is started. -- Once the application is initialized and registered in the server container, the -- state is changed to <tt>READY</tt>. type Configure_State is (CONFIGURING, STARTING, READY); -- Maintains the state of the configuration between the main task and the http configuration -- requests. protected type State is -- Wait until the configuration is finished. entry Wait_Configuring; -- Wait until the server application is initialized and ready. entry Wait_Ready; -- Set the configuration state. procedure Set (V : in Configure_State); private Value : Configure_State := CONFIGURING; end State; type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased Servlet.Core.Files.File_Servlet; Redirect : aliased Redirect_Servlet; Config : ASF.Applications.Config; Changed : ASF.Applications.Config; Factory : ASF.Applications.Main.Application_Factory; Path : Ada.Strings.Unbounded.Unbounded_String; Database : ADO.Drivers.Connections.Configuration; Driver : Util.Beans.Objects.Object; Result : Util.Beans.Objects.Object; Root_User : Util.Beans.Objects.Object := Empty; Root_Passwd : Util.Beans.Objects.Object := Empty; Db_Host : Util.Beans.Objects.Object; Db_Port : Util.Beans.Objects.Object; Has_Error : Boolean := False; Status : State; end record; -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the database connection string to be used by the application. function Get_Database_URL (From : in Application) return String; -- Get the command to configure the database. function Get_Configure_Command (From : in Application) return String; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Validate the database configuration parameters. procedure Validate (From : in out Application); -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup to start the application. procedure Start (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup and wait for the application to be started. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class); -- Configure the application by using the setup application, allowing the administrator to -- setup the application database, define the application admin parameters. After the -- configuration is done, register the application in the server container and start it. generic type Application_Type (<>) is new ASF.Servlets.Servlet_Registry with private; type Application_Access is access all Application_Type'Class; with procedure Initialize (App : in Application_Access; Config : in ASF.Applications.Config); procedure Configure (Server : in out ASF.Server.Container'Class; App : in Application_Access; Config : in String; URI : in String); end AWA.Setup.Applications;
----------------------------------------------------------------------- -- awa-setup-applications -- Setup and installation -- Copyright (C) 2016, 2017, 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 ASF.Applications.Main; with ASF.Servlets.Faces; with Servlet.Core.Files; with ASF.Requests; with ASF.Responses; with ASF.Server; with ADO.Connections; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; -- == Setup Procedure Instantiation== -- The setup process is managed by the *Configure* generic procedure. The procedure must -- be instantiated with the application class type and the application initialize procedure. -- -- procedure Setup is -- new AWA.Setup.Applications.Configure (MyApp.Application'Class, -- MyApp.Application_Access, -- MyApp.Initialize); -- -- == Setup Operation == -- The *Setup* instantiated operation must then be called with the web container. -- The web container is started first and the *Setup* procedure gets as parameter the -- web container, the application instance to configure, the application name and -- the application context path. -- -- Setup (WS, App, "atlas", MyApp.CONTEXT_PATH) -- -- The operation will install the setup application to handle the setup actions. Through -- the setup actions, the installer will be able to: -- -- * Configure the database (MySQL or SQLite), -- * Configure the Google+ and Facebook OAuth authentication keys, -- * Configure the application name, -- * Configure the mail parameters to be able to send email. -- -- After the setup and configure is finished, the file <tt>.initialized</tt> is created in -- the application directory to indicate the application is configured. The next time the -- *Setup* operation is called, the installation process will be skipped. -- -- To run again the installation, remove manually the <tt>.initialized</tt> file. package AWA.Setup.Applications is Empty : constant Util.Beans.Objects.Object := Util.Beans.Objects.To_Object (String '("")); -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Redirect_Servlet is new Servlet.Core.Servlet with null record; overriding procedure Do_Get (Server : in Redirect_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- The configuration state starts in the <tt>CONFIGURING</tt> state and moves to the -- <tt>STARTING</tt> state after the application is configured and it is started. -- Once the application is initialized and registered in the server container, the -- state is changed to <tt>READY</tt>. type Configure_State is (CONFIGURING, STARTING, READY); -- Maintains the state of the configuration between the main task and the http configuration -- requests. protected type State is -- Wait until the configuration is finished. entry Wait_Configuring; -- Wait until the server application is initialized and ready. entry Wait_Ready; -- Set the configuration state. procedure Set (V : in Configure_State); private Value : Configure_State := CONFIGURING; end State; type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased Servlet.Core.Files.File_Servlet; Redirect : aliased Redirect_Servlet; Config : ASF.Applications.Config; Changed : ASF.Applications.Config; Factory : ASF.Applications.Main.Application_Factory; Path : Ada.Strings.Unbounded.Unbounded_String; Database : ADO.Connections.Configuration; Driver : Util.Beans.Objects.Object; Result : Util.Beans.Objects.Object; Root_User : Util.Beans.Objects.Object := Empty; Root_Passwd : Util.Beans.Objects.Object := Empty; Db_Host : Util.Beans.Objects.Object; Db_Port : Util.Beans.Objects.Object; Has_Error : Boolean := False; Status : State; end record; -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the database connection string to be used by the application. function Get_Database_URL (From : in Application) return String; -- Get the command to configure the database. function Get_Configure_Command (From : in Application) return String; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Validate the database configuration parameters. procedure Validate (From : in out Application); -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup to start the application. procedure Start (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup and wait for the application to be started. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class); -- Configure the application by using the setup application, allowing the administrator to -- setup the application database, define the application admin parameters. After the -- configuration is done, register the application in the server container and start it. generic type Application_Type (<>) is new ASF.Servlets.Servlet_Registry with private; type Application_Access is access all Application_Type'Class; with procedure Initialize (App : in Application_Access; Config : in ASF.Applications.Config); procedure Configure (Server : in out ASF.Server.Container'Class; App : in Application_Access; Config : in String; URI : in String); end AWA.Setup.Applications;
Rename ADO.Drivers.Connections into ADO.Connections
Rename ADO.Drivers.Connections into ADO.Connections
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
52fdf3983354918e144293f8d30c4fb410d9b8c4
src/util-concurrent-arrays.adb
src/util-concurrent-arrays.adb
----------------------------------------------------------------------- -- Util.Concurrent.Arrays -- Concurrent Arrays -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Concurrent.Arrays is procedure Free is new Ada.Unchecked_Deallocation (Object => Vector_Record, Name => Vector_Record_Access); -- ------------------------------ -- Returns True if the container is empty. -- ------------------------------ function Is_Empty (Container : in Ref) return Boolean is begin return Container.Target = null; end Is_Empty; -- ------------------------------ -- Iterate over the vector elements and execute the <b>Process</b> procedure -- with the element as parameter. -- ------------------------------ procedure Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)) is Target : constant Vector_Record_Access := Container.Target; begin if Target /= null then for I in Target.List'Range loop Process (Target.List (I)); end loop; end if; end Iterate; -- ------------------------------ -- Iterate over the vector elements in reverse order and execute the <b>Process</b> procedure -- with the element as parameter. -- ------------------------------ procedure Reverse_Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)) is Target : constant Vector_Record_Access := Container.Target; begin if Target /= null then for I in reverse Target.List'Range loop Process (Target.List (I)); end loop; end if; end Reverse_Iterate; -- ------------------------------ -- 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 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; -- ------------------------------ -- Get a read-only reference to the vector elements. The referenced vector will never -- be modified. -- ------------------------------ function Get (Container : in Vector'Class) return Ref is begin return Container.List.Get; end Get; -- ------------------------------ -- Append the element to the vector. The modification will not be visible to readers -- until they call the <b>Get</b> function. -- ------------------------------ procedure Append (Container : in out Vector; Item : in Element_Type) is begin Container.List.Append (Item); end Append; -- ------------------------------ -- Remove the element represented by <b>Item</b> from the vector. The modification will -- not be visible to readers until they call the <b>Get</b> function. -- ------------------------------ procedure Remove (Container : in out Vector; Item : in Element_Type) is begin Container.List.Remove (Item); end Remove; -- Release the vector elements. overriding procedure Finalize (Object : in out Vector) is begin null; end Finalize; -- Vector of objects protected body Protected_Vector is -- ------------------------------ -- Get a readonly reference to the vector. -- ------------------------------ function Get return Ref is begin return Elements; end Get; -- ------------------------------ -- Append the element to the vector. -- ------------------------------ procedure Append (Item : in Element_Type) is New_Items : Vector_Record_Access; Len : Natural; begin if Elements.Target = null then New_Items := new Vector_Record (Len => 1); Len := 1; else Len := Elements.Target.Len + 1; New_Items := new Vector_Record (Len => Len); New_Items.List (1 .. Len - 1) := Elements.Target.List; Finalize (Elements); end if; New_Items.List (Len) := Item; Util.Concurrent.Counters.Increment (New_Items.Ref_Counter); Elements.Target := New_Items; end Append; -- ------------------------------ -- Remove the element from the vector. -- ------------------------------ procedure Remove (Item : in Element_Type) is New_Items : Vector_Record_Access; Items : constant Vector_Record_Access := Elements.Target; begin if Items = null then return; end if; for I in Items.List'Range loop if Items.List (I) = Item then if Items.Len = 1 then Finalize (Elements); Elements.Target := null; else New_Items := new Vector_Record (Len => Items.Len - 1); if I > 1 then New_Items.List (1 .. I - 1) := Items.List (1 .. I - 1); end if; if I <= New_Items.List'Last then New_Items.List (I .. New_Items.List'Last) := Items.List (I + 1 .. Items.List'Last); end if; Finalize (Elements); Util.Concurrent.Counters.Increment (New_Items.Ref_Counter); Elements.Target := New_Items; end if; return; end if; end loop; end Remove; end Protected_Vector; end Util.Concurrent.Arrays;
----------------------------------------------------------------------- -- util-concurrent-arrays -- Concurrent Arrays -- Copyright (C) 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Concurrent.Arrays is procedure Free is new Ada.Unchecked_Deallocation (Object => Vector_Record, Name => Vector_Record_Access); -- ------------------------------ -- Returns True if the container is empty. -- ------------------------------ function Is_Empty (Container : in Ref) return Boolean is begin return Container.Target = null; end Is_Empty; -- ------------------------------ -- Iterate over the vector elements and execute the <b>Process</b> procedure -- with the element as parameter. -- ------------------------------ procedure Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)) is Target : constant Vector_Record_Access := Container.Target; begin if Target /= null then for I in Target.List'Range loop Process (Target.List (I)); end loop; end if; end Iterate; -- ------------------------------ -- Iterate over the vector elements in reverse order and execute the <b>Process</b> procedure -- with the element as parameter. -- ------------------------------ procedure Reverse_Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)) is Target : constant Vector_Record_Access := Container.Target; begin if Target /= null then for I in reverse Target.List'Range loop Process (Target.List (I)); end loop; end if; end Reverse_Iterate; -- ------------------------------ -- 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 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; -- ------------------------------ -- Get a read-only reference to the vector elements. The referenced vector will never -- be modified. -- ------------------------------ function Get (Container : in Vector'Class) return Ref is begin return Container.List.Get; end Get; -- ------------------------------ -- Append the element to the vector. The modification will not be visible to readers -- until they call the <b>Get</b> function. -- ------------------------------ procedure Append (Container : in out Vector; Item : in Element_Type) is begin Container.List.Append (Item); end Append; -- ------------------------------ -- Remove the element represented by <b>Item</b> from the vector. The modification will -- not be visible to readers until they call the <b>Get</b> function. -- ------------------------------ procedure Remove (Container : in out Vector; Item : in Element_Type) is begin Container.List.Remove (Item); end Remove; -- Release the vector elements. overriding procedure Finalize (Object : in out Vector) is begin null; end Finalize; -- Vector of objects protected body Protected_Vector is -- ------------------------------ -- Get a readonly reference to the vector. -- ------------------------------ function Get return Ref is begin return Elements; end Get; -- ------------------------------ -- Append the element to the vector. -- ------------------------------ procedure Append (Item : in Element_Type) is New_Items : Vector_Record_Access; Len : Natural; begin if Elements.Target = null then New_Items := new Vector_Record (Len => 1); Len := 1; else Len := Elements.Target.Len + 1; New_Items := new Vector_Record (Len => Len); New_Items.List (1 .. Len - 1) := Elements.Target.List; Finalize (Elements); end if; New_Items.List (Len) := Item; Util.Concurrent.Counters.Increment (New_Items.Ref_Counter); Elements.Target := New_Items; end Append; -- ------------------------------ -- Remove the element from the vector. -- ------------------------------ procedure Remove (Item : in Element_Type) is New_Items : Vector_Record_Access; Items : constant Vector_Record_Access := Elements.Target; begin if Items = null then return; end if; for I in Items.List'Range loop if Items.List (I) = Item then if Items.Len = 1 then Finalize (Elements); Elements.Target := null; else New_Items := new Vector_Record (Len => Items.Len - 1); if I > 1 then New_Items.List (1 .. I - 1) := Items.List (1 .. I - 1); end if; if I <= New_Items.List'Last then New_Items.List (I .. New_Items.List'Last) := Items.List (I + 1 .. Items.List'Last); end if; Finalize (Elements); Util.Concurrent.Counters.Increment (New_Items.Ref_Counter); Elements.Target := New_Items; end if; return; end if; end loop; end Remove; end Protected_Vector; end Util.Concurrent.Arrays;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d089824ca1c6d23300bd16c4ccb347571e7596d7
samples/demo_server.adb
samples/demo_server.adb
----------------------------------------------------------------------- -- demo_server -- Demo server for Ada Server Faces -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with ASF.Server.Web; with ASF.Servlets; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Measures; with ASF.Filters.Dump; with ASF.Beans; with ASF.Applications; with ASF.Applications.Main; with ASF.Applications.Main.Configs; with ASF.Security.Servlets; with Util.Beans.Objects; with Util.Log.Loggers; with AWS.Net.SSL; with Upload_Servlet; with Countries; with Volume; with Messages; with Facebook; -- with Images; with Users; procedure Demo_Server is CONTEXT_PATH : constant String := "/demo"; CONFIG_PATH : constant String := "samples.properties"; Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid"); Factory : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; -- Application servlets. App : aliased ASF.Applications.Main.Application; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased ASF.Security.Servlets.Verify_Auth_Servlet; Perf : aliased ASF.Servlets.Measures.Measure_Servlet; Upload : aliased Upload_Servlet.Servlet; -- Debug filters. Dump : aliased ASF.Filters.Dump.Dump_Filter; FB_Auth : aliased Facebook.Facebook_Auth; Bean : aliased Volume.Compute_Bean; Conv : aliased Volume.Float_Converter; None : ASF.Beans.Parameter_Bean_Ref.Ref; -- Web application server WS : ASF.Server.Web.AWS_Container; begin if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); return; end if; C.Set (ASF.Applications.VIEW_EXT, ".html"); C.Set (ASF.Applications.VIEW_DIR, "samples/web"); C.Set ("web.dir", "samples/web"); begin C.Load_Properties (CONFIG_PATH); Util.Log.Loggers.Initialize (CONFIG_PATH); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; C.Set ("contextPath", CONTEXT_PATH); App.Initialize (C, Factory); App.Set_Global ("contextPath", CONTEXT_PATH); App.Set_Global ("compute", Util.Beans.Objects.To_Object (Bean'Unchecked_Access, Util.Beans.Objects.STATIC)); FB_Auth.Set_Application_Identifier (C.Get ("facebook.client_id")); FB_Auth.Set_Application_Secret (C.Get ("facebook.secret")); FB_Auth.Set_Application_Callback (C.Get ("facebook.callback")); FB_Auth.Set_Provider_URI ("https://graph.facebook.com/oauth/access_token"); App.Set_Global ("facebook", Util.Beans.Objects.To_Object (FB_Auth'Unchecked_Access, Util.Beans.Objects.STATIC)); App.Set_Global ("countries", Util.Beans.Objects.To_Object (Countries.Create_Country_List)); App.Set_Global ("user", Util.Beans.Objects.To_Object (Users.User'Access, Util.Beans.Objects.STATIC)); -- Declare a global bean to identify this sample from within the XHTML files. App.Set_Global ("sampleName", "volume"); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access); App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access); App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access); App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access); App.Add_Servlet (Name => "upload", Server => Upload'Unchecked_Access); App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.png"); App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify"); App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*"); App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml"); App.Add_Mapping (Name => "upload", Pattern => "upload.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.js"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*"); App.Add_Converter (Name => "float", Converter => Conv'Unchecked_Access); -- App.Register_Class (Name => "Image_Bean", Handler => Images.Create_Image_Bean'Access); App.Register_Class (Name => "Message_Bean", Handler => Messages.Create_Message_Bean'Access); App.Register_Class (Name => "Message_List", Handler => Messages.Create_Message_List'Access); App.Register_Class (Name => "Friends_Bean", Handler => Facebook.Create_Friends_Bean'Access); App.Register_Class (Name => "Feeds_Bean", Handler => Facebook.Create_Feed_List_Bean'Access); App.Register (Name => "message", Class => "Message_Bean", Params => None); App.Register (Name => "messages", Class => "Message_List", Params => None); App.Register (Name => "image", Class => "Image_Bean", Params => None); ASF.Applications.Main.Configs.Read_Configuration (App, "samples/web/WEB-INF/web.xml"); WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/demo/compute.html"); WS.Start; delay 6000.0; end Demo_Server;
----------------------------------------------------------------------- -- demo_server -- Demo server for Ada Server Faces -- 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 Ada.IO_Exceptions; with ASF.Server.Web; with ASF.Servlets; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Measures; with ASF.Filters.Dump; with ASF.Beans; with ASF.Applications; with ASF.Applications.Main; with ASF.Applications.Main.Configs; with ASF.Security.Servlets; with Util.Beans.Objects; with Util.Log.Loggers; with AWS.Net.SSL; with Upload_Servlet; with Countries; with Volume; with Messages; with Facebook; -- with Images; with Users; procedure Demo_Server is CONTEXT_PATH : constant String := "/demo"; CONFIG_PATH : constant String := "samples.properties"; Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid"); Factory : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; -- Application servlets. App : aliased ASF.Applications.Main.Application; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased ASF.Security.Servlets.Verify_Auth_Servlet; Perf : aliased ASF.Servlets.Measures.Measure_Servlet; Upload : aliased Upload_Servlet.Servlet; -- Debug filters. Dump : aliased ASF.Filters.Dump.Dump_Filter; FB_Auth : aliased Facebook.Facebook_Auth; Bean : aliased Volume.Compute_Bean; Conv : aliased Volume.Float_Converter; None : ASF.Beans.Parameter_Bean_Ref.Ref; -- Web application server WS : ASF.Server.Web.AWS_Container; begin if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); return; end if; C.Set (ASF.Applications.VIEW_EXT, ".html"); C.Set (ASF.Applications.VIEW_DIR, "samples/web"); C.Set ("web.dir", "samples/web"); begin C.Load_Properties (CONFIG_PATH); Util.Log.Loggers.Initialize (CONFIG_PATH); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; C.Set ("contextPath", CONTEXT_PATH); App.Initialize (C, Factory); App.Set_Global ("contextPath", CONTEXT_PATH); App.Set_Global ("compute", Util.Beans.Objects.To_Object (Bean'Unchecked_Access, Util.Beans.Objects.STATIC)); FB_Auth.Set_Application_Identifier (C.Get ("facebook.client_id")); FB_Auth.Set_Application_Secret (C.Get ("facebook.secret")); FB_Auth.Set_Application_Callback (C.Get ("facebook.callback")); FB_Auth.Set_Provider_URI ("https://graph.facebook.com/oauth/access_token"); App.Set_Global ("facebook", Util.Beans.Objects.To_Object (FB_Auth'Unchecked_Access, Util.Beans.Objects.STATIC)); App.Set_Global ("countries", Util.Beans.Objects.To_Object (Countries.Create_Country_List)); App.Set_Global ("user", Util.Beans.Objects.To_Object (Users.User'Access, Util.Beans.Objects.STATIC)); -- Declare a global bean to identify this sample from within the XHTML files. App.Set_Global ("sampleName", "volume"); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access); App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access); App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access); App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access); App.Add_Servlet (Name => "upload", Server => Upload'Unchecked_Access); App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.png"); App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify"); App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*"); App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml"); App.Add_Mapping (Name => "upload", Pattern => "upload.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.js"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*"); App.Add_Converter (Name => "float", Converter => Conv'Unchecked_Access); -- App.Register_Class (Name => "Image_Bean", Handler => Images.Create_Image_Bean'Access); App.Register_Class (Name => "Message_Bean", Handler => Messages.Create_Message_Bean'Access); App.Register_Class (Name => "Message_List", Handler => Messages.Create_Message_List'Access); App.Register_Class (Name => "Friends_Bean", Handler => Facebook.Create_Friends_Bean'Access); App.Register_Class (Name => "Feeds_Bean", Handler => Facebook.Create_Feed_List_Bean'Access); App.Register (Name => "message", Class => "Message_Bean", Params => None); App.Register (Name => "messages", Class => "Message_List", Params => None); ASF.Applications.Main.Configs.Read_Configuration (App, "samples/web/WEB-INF/web.xml"); WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/demo/compute.html"); WS.Start; delay 6000.0; end Demo_Server;
Fix error when the demo is started
Fix error when the demo is started
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
a287b816ea46fde2cb63009fde08eda030ef6278
src/natools-web-containers.ads
src/natools-web-containers.ads
------------------------------------------------------------------------------ -- Copyright (c) 2014-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Containres provides common containers for all website-wide -- -- persistent data. -- ------------------------------------------------------------------------------ with Ada.Calendar.Time_Zones; with Ada.Containers.Doubly_Linked_Lists; with Ada.Containers.Indefinite_Doubly_Linked_Lists; with Ada.Streams; with Natools.Constant_Indefinite_Ordered_Maps; with Natools.References; with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Caches; with Natools.S_Expressions.Lockable; with Natools.Storage_Pools; package Natools.Web.Containers is type Date is record Time : Ada.Calendar.Time; Offset : Ada.Calendar.Time_Zones.Time_Offset; end record; package Date_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, Date, S_Expressions.Less_Than); procedure Set_Dates (Map : in out Date_Maps.Constant_Map; Date_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize date database with then given list package Expression_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, S_Expressions.Caches.Cursor, S_Expressions.Less_Than, S_Expressions.Caches."="); procedure Set_Expressions (Map : in out Expression_Maps.Constant_Map; Expression_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize expression database with the given list package Expression_Map_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, Expression_Maps.Constant_Map, S_Expressions.Less_Than, Expression_Maps."="); procedure Set_Expression_Maps (Map : in out Expression_Map_Maps.Constant_Map; Expression_Map_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize expression map database with the given list package Unsafe_Atom_Lists is new Ada.Containers.Indefinite_Doubly_Linked_Lists (S_Expressions.Atom, Ada.Streams."="); procedure Append_Atoms (Target : in out Unsafe_Atom_Lists.List; Expression : in out S_Expressions.Lockable.Descriptor'Class); type Atom_Array is array (S_Expressions.Count range <>) of S_Expressions.Atom_Refs.Immutable_Reference; package Atom_Array_Refs is new References (Atom_Array, Storage_Pools.Access_In_Default_Pool'Storage_Pool, Storage_Pools.Access_In_Default_Pool'Storage_Pool); function Create (Source : Unsafe_Atom_Lists.List) return Atom_Array_Refs.Immutable_Reference; function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Array_Refs.Immutable_Reference; package Atom_Row_Lists is new Ada.Containers.Doubly_Linked_Lists (Atom_Array_Refs.Immutable_Reference, Atom_Array_Refs."="); type Atom_Table is array (S_Expressions.Offset range <>) of Atom_Array_Refs.Immutable_Reference; package Atom_Table_Refs is new References (Atom_Table, Natools.Storage_Pools.Access_In_Default_Pool'Storage_Pool, Natools.Storage_Pools.Access_In_Default_Pool'Storage_Pool); function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Table_Refs.Immutable_Reference; function Create (Row_List : in Atom_Row_Lists.List) return Atom_Table_Refs.Immutable_Reference; type Atom_Set is private; function Create (Source : in Atom_Array) return Atom_Set; function Create (Source : in Unsafe_Atom_Lists.List) return Atom_Set; function Contains (Set : in Atom_Set; Value : in S_Expressions.Atom) return Boolean; function Contains (Set : in Atom_Set; Value : in String) return Boolean; type Identity is record User : S_Expressions.Atom_Refs.Immutable_Reference; Groups : Atom_Set; end record; private type Atom_Set is record Elements : Atom_Array_Refs.Immutable_Reference; end record; end Natools.Web.Containers;
------------------------------------------------------------------------------ -- Copyright (c) 2014-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Containres provides common containers for all website-wide -- -- persistent data. -- ------------------------------------------------------------------------------ with Ada.Calendar.Time_Zones; with Ada.Containers.Doubly_Linked_Lists; with Ada.Containers.Indefinite_Doubly_Linked_Lists; with Ada.Streams; with Natools.Constant_Indefinite_Ordered_Maps; with Natools.References; with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Caches; with Natools.S_Expressions.Lockable; with Natools.Storage_Pools; package Natools.Web.Containers is type Date is record Time : Ada.Calendar.Time; Offset : Ada.Calendar.Time_Zones.Time_Offset; end record; package Date_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, Date, S_Expressions.Less_Than); procedure Set_Dates (Map : in out Date_Maps.Constant_Map; Date_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize date database with then given list package Expression_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, S_Expressions.Caches.Cursor, S_Expressions.Less_Than, S_Expressions.Caches."="); procedure Set_Expressions (Map : in out Expression_Maps.Constant_Map; Expression_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize expression database with the given list package Expression_Map_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, Expression_Maps.Constant_Map, S_Expressions.Less_Than, Expression_Maps."="); procedure Set_Expression_Maps (Map : in out Expression_Map_Maps.Constant_Map; Expression_Map_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize expression map database with the given list package Unsafe_Atom_Lists is new Ada.Containers.Indefinite_Doubly_Linked_Lists (S_Expressions.Atom, Ada.Streams."="); procedure Append_Atoms (Target : in out Unsafe_Atom_Lists.List; Expression : in out S_Expressions.Lockable.Descriptor'Class); type Atom_Array is array (S_Expressions.Count range <>) of S_Expressions.Atom_Refs.Immutable_Reference; package Atom_Array_Refs is new References (Atom_Array, Storage_Pools.Access_In_Default_Pool'Storage_Pool, Storage_Pools.Access_In_Default_Pool'Storage_Pool); function Create (Source : Unsafe_Atom_Lists.List) return Atom_Array_Refs.Immutable_Reference; function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Array_Refs.Immutable_Reference; package Atom_Row_Lists is new Ada.Containers.Doubly_Linked_Lists (Atom_Array_Refs.Immutable_Reference, Atom_Array_Refs."="); type Atom_Table is array (S_Expressions.Offset range <>) of Atom_Array_Refs.Immutable_Reference; package Atom_Table_Refs is new References (Atom_Table, Natools.Storage_Pools.Access_In_Default_Pool'Storage_Pool, Natools.Storage_Pools.Access_In_Default_Pool'Storage_Pool); function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Table_Refs.Immutable_Reference; function Create (Row_List : in Atom_Row_Lists.List) return Atom_Table_Refs.Immutable_Reference; type Atom_Set is private; Null_Atom_Set : constant Atom_Set; function Create (Source : in Atom_Array) return Atom_Set; function Create (Source : in Unsafe_Atom_Lists.List) return Atom_Set; function Contains (Set : in Atom_Set; Value : in S_Expressions.Atom) return Boolean; function Contains (Set : in Atom_Set; Value : in String) return Boolean; type Identity is record User : S_Expressions.Atom_Refs.Immutable_Reference; Groups : Atom_Set; end record; Null_Identity : constant Identity; private type Atom_Set is record Elements : Atom_Array_Refs.Immutable_Reference; end record; Null_Atom_Set : constant Atom_Set := (Elements => Atom_Array_Refs.Null_Immutable_Reference); Null_Identity : constant Identity := (User => S_Expressions.Atom_Refs.Null_Immutable_Reference, Groups => Null_Atom_Set); end Natools.Web.Containers;
add null constants for atom set and identity
containers: add null constants for atom set and identity
Ada
isc
faelys/natools-web,faelys/natools-web
01ae2e64404880ccb068a34f2d9ca074732ca663
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Events.Faces.Actions; with ADO.Utils; with ADO.Sessions.Entities; with ADO.Sessions; with ADO.Queries; with ADO.Datasets; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Events.Action_Method; with AWA.Services.Contexts; package body AWA.Workspaces.Beans is package ASC renames AWA.Services.Contexts; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Load; overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Accept_Invitation; overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Send_Invitation (Bean); end Send; -- ------------------------------ -- Create the Invitation_Bean bean instance. -- ------------------------------ function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Invitation_Bean_Access := new Invitation_Bean; begin Object.Module := Module; return Object; end Create_Invitation_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Action; -- ------------------------------ -- Event action called to create the workspace when the given event is posted. -- ------------------------------ procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Bean, Event); WS : AWA.Workspaces.Models.Workspace_Ref; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (Session => DB, Context => Ctx, Workspace => WS); Ctx.Commit; end Create; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean, Method => Action, Name => "action"); package Create_Binding is new AWA.Events.Action_Method.Bind (Name => "create", Bean => Workspaces_Bean, Method => Create); Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Workspaces_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Workspaces_Bean_Access := new Workspaces_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Workspaces_Bean; -- ------------------------------ -- Load the list of members. -- ------------------------------ overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Into.Module.Get_Session; Query : ADO.Queries.Context; Count_Query : ADO.Queries.Context; First : constant Natural := (Into.Page - 1) * Into.Page_Size; begin Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "page_table", -- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, -- Session => Session); Query.Bind_Param (Name => "user_id", Value => User); Count_Query.Bind_Param (Name => "user_id", Value => User); AWA.Workspaces.Models.List (Into.Members, Session, Query); Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); end Load; -- ------------------------------ -- Create the Member_List_Bean bean instance. -- ------------------------------ function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_List_Bean_Access := new Member_List_Bean; begin Object.Module := Module; Object.Members_Bean := Object.Members'Access; Object.Page_Size := 20; Object.Page := 1; Object.Count := 0; return Object.all'Access; end Create_Member_List_Bean; end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Events.Faces.Actions; with ADO.Utils; with ADO.Sessions.Entities; with ADO.Sessions; with ADO.Queries; with ADO.Datasets; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Events.Action_Method; with AWA.Services.Contexts; package body AWA.Workspaces.Beans is package ASC renames AWA.Services.Contexts; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key), Invitation => Bean); exception when others => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Accept_Invitation; overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Send_Invitation (Bean); end Send; -- ------------------------------ -- Create the Invitation_Bean bean instance. -- ------------------------------ function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Invitation_Bean_Access := new Invitation_Bean; begin Object.Module := Module; return Object; end Create_Invitation_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Action; -- ------------------------------ -- Event action called to create the workspace when the given event is posted. -- ------------------------------ procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Bean, Event); WS : AWA.Workspaces.Models.Workspace_Ref; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (Session => DB, Context => Ctx, Workspace => WS); Ctx.Commit; end Create; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean, Method => Action, Name => "action"); package Create_Binding is new AWA.Events.Action_Method.Bind (Name => "create", Bean => Workspaces_Bean, Method => Create); Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Workspaces_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Workspaces_Bean_Access := new Workspaces_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Workspaces_Bean; -- ------------------------------ -- Load the list of members. -- ------------------------------ overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Into.Module.Get_Session; Query : ADO.Queries.Context; Count_Query : ADO.Queries.Context; First : constant Natural := (Into.Page - 1) * Into.Page_Size; begin Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "page_table", -- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, -- Session => Session); Query.Bind_Param (Name => "user_id", Value => User); Count_Query.Bind_Param (Name => "user_id", Value => User); AWA.Workspaces.Models.List (Into.Members, Session, Query); Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); end Load; -- ------------------------------ -- Create the Member_List_Bean bean instance. -- ------------------------------ function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_List_Bean_Access := new Member_List_Bean; begin Object.Module := Module; Object.Members_Bean := Object.Members'Access; Object.Page_Size := 20; Object.Page := 1; Object.Count := 0; return Object.all'Access; end Create_Member_List_Bean; end AWA.Workspaces.Beans;
Implement the Load invitation procedure and use the Load_Invitation workspace module operation
Implement the Load invitation procedure and use the Load_Invitation workspace module operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c71d8a04cd8e4e2c1e82c4256714ee7375a44886
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with AWA.Tests; with AWA.Tests.Helpers; with AWA.Tests.Helpers.Users; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Wikis.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space", Test_Create_Wiki_Space'Access); end Add_Tests; -- ------------------------------ -- Test creation of a wiki space. -- ------------------------------ procedure Test_Create_Wiki_Space (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; W2 : AWA.Wikis.Models.Wiki_Space_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Wikis.Modules.Get_Wiki_Module; T.Assert (T.Manager /= null, "There is no wiki manager"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); T.Assert (W.Is_Inserted, "The new wiki space was not created"); W.Set_Name ("Test wiki space update"); W.Set_Is_Public (True); T.Manager.Save_Wiki_Space (W); T.Manager.Load_Wiki_Space (Wiki => W2, Id => W.Get_Id); Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name), "Invalid wiki space name"); end Test_Create_Wiki_Space; end AWA.Wikis.Modules.Tests;
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with AWA.Tests; with AWA.Tests.Helpers; with AWA.Tests.Helpers.Users; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Wikis.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space", Test_Create_Wiki_Space'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page", Test_Create_Wiki_Page'Access); end Add_Tests; -- ------------------------------ -- Test creation of a wiki space. -- ------------------------------ procedure Test_Create_Wiki_Space (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; W2 : AWA.Wikis.Models.Wiki_Space_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Wikis.Modules.Get_Wiki_Module; T.Assert (T.Manager /= null, "There is no wiki manager"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); T.Assert (W.Is_Inserted, "The new wiki space was not created"); W.Set_Name ("Test wiki space update"); W.Set_Is_Public (True); T.Manager.Save_Wiki_Space (W); T.Manager.Load_Wiki_Space (Wiki => W2, Id => W.Get_Id); Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name), "Invalid wiki space name"); end Test_Create_Wiki_Space; -- ------------------------------ -- Test creation of a wiki page. -- ------------------------------ procedure Test_Create_Wiki_Page (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; P : AWA.Wikis.Models.Wiki_Page_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); P.Set_Name ("The page"); P.Set_Title ("The page title"); T.Manager.Create_Wiki_Page (W, P); end Test_Create_Wiki_Page; end AWA.Wikis.Modules.Tests;
Implement Test_Create_Wiki_Page unit test
Implement Test_Create_Wiki_Page unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
cf76cbc650a71588d1e48d58511aa0c58acb005c
awa/plugins/awa-mail/src/awa-mail-clients-files.adb
awa/plugins/awa-mail/src/awa-mail-clients-files.adb
----------------------------------------------------------------------- -- awa-mail-clients-files -- Mail client dump/file implementation -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Util.Files; with Util.Strings; with Util.Log.Loggers; package body AWA.Mail.Clients.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.Files"); -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out File_Mail_Message; Name : in String; Address : in String) is begin Message.From := To_Unbounded_String ("From: " & Name & " <" & Address & ">"); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out File_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is Email : constant String := Name & " <" & Address & ">"; begin case Kind is when TO => if Length (Message.To) = 0 then Append (Message.To, "To: "); else Append (Message.To, ", "); end if; Append (Message.To, Email); when CC => if Length (Message.Cc) = 0 then Append (Message.Cc, "Cc: "); else Append (Message.Cc, ", "); end if; Append (Message.Cc, Email); when BCC => if Length (Message.Bcc) = 0 then Append (Message.Bcc, "Bcc: "); else Append (Message.Bcc, ", "); end if; Append (Message.Bcc, Email); end case; end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out File_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out File_Mail_Message; Content : in Unbounded_String; Alternative : in Unbounded_String; Content_Type : in String) is begin if Length (Alternative) > 0 then Append (Message.Message, "Content-Type: multipart/alternative; boundary=AAA" & ASCII.LF & ASCII.LF); Append (Message.Message, "--AAA" & ASCII.LF); end if; Append (Message.Message, "Content-Type: "); Append (Message.Message, Content_Type); Append (Message.Message, ASCII.LF); Append (Message.Message, Content); if Length (Alternative) > 0 then Append (Message.Message, ASCII.LF & "--AAA" & ASCII.LF); Append (Message.Message, "Content-Type: text/plain; charset=utf-8" & ASCII.LF); Append (Message.Message, Alternative); Append (Message.Message, ASCII.LF & "--AAA" & ASCII.LF); end if; end Set_Body; -- ------------------------------ -- Add an attachment with the given content. -- ------------------------------ overriding procedure Add_Attachment (Message : in out File_Mail_Message; Content : in Unbounded_String; Content_Id : in String; Content_Type : in String) is begin Append (Message.Message, "Content-Type: "); Append (Message.Message, Content_Type); Append (Message.Message, "; boundary=BBB"); Append (Message.Message, ASCII.LF); if Content_Id'Length > 0 then Append (Message.Message, "Content-Id: "); Append (Message.Message, Content_Id); Append (Message.Message, ASCII.LF); end if; Append (Message.Message, "==BBB" & ASCII.LF); Append (Message.Message, Content); Append (Message.Message, "==BBB" & ASCII.LF); end Add_Attachment; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out File_Mail_Message) is N : Natural; Output : Ada.Text_IO.File_Type; begin Util.Concurrent.Counters.Increment (Message.Manager.Index, N); declare Path : constant String := Util.Files.Compose (To_String (Message.Manager.Path), "msg-" & Util.Strings.Image (N)); begin Log.Info ("Sending dumb mail to {0}", Path); Ada.Text_IO.Create (File => Output, Mode => Ada.Text_IO.Out_File, Name => Path); Ada.Text_IO.Put_Line (Output, To_String (Message.From)); if Length (Message.To) > 0 then Ada.Text_IO.Put_Line (Output, To_String (Message.To)); end if; if Length (Message.Cc) > 0 then Ada.Text_IO.Put_Line (Output, To_String (Message.Cc)); end if; if Length (Message.Bcc) > 0 then Ada.Text_IO.Put_Line (Output, To_String (Message.Bcc)); end if; Ada.Text_IO.Put (Output, "Subject: "); Ada.Text_IO.Put_Line (Output, To_String (Message.Subject)); Ada.Text_IO.Put_Line (Output, To_String (Message.Message)); Ada.Text_IO.Put_Line (Output, To_String (Message.Attachments)); Ada.Text_IO.Close (Output); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot create mail file {0}", Path); end; end Send; -- ------------------------------ -- Create a file based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Result : constant File_Mail_Manager_Access := new File_Mail_Manager; begin Result.Self := Result; Result.Path := To_Unbounded_String (Props.Get (NAME & ".maildir", "mail")); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in File_Mail_Manager) return Mail_Message_Access is Result : constant File_Mail_Message_Access := new File_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.Files;
----------------------------------------------------------------------- -- awa-mail-clients-files -- Mail client dump/file implementation -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Util.Files; with Util.Strings; with Util.Log.Loggers; package body AWA.Mail.Clients.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.Files"); -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out File_Mail_Message; Name : in String; Address : in String) is begin Message.From := To_Unbounded_String ("From: " & Name & " <" & Address & ">"); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out File_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is Email : constant String := Name & " <" & Address & ">"; begin case Kind is when TO => if Length (Message.To) = 0 then Append (Message.To, "To: "); else Append (Message.To, ", "); end if; Append (Message.To, Email); when CC => if Length (Message.Cc) = 0 then Append (Message.Cc, "Cc: "); else Append (Message.Cc, ", "); end if; Append (Message.Cc, Email); when BCC => if Length (Message.Bcc) = 0 then Append (Message.Bcc, "Bcc: "); else Append (Message.Bcc, ", "); end if; Append (Message.Bcc, Email); end case; end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out File_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out File_Mail_Message; Content : in Unbounded_String; Alternative : in Unbounded_String; Content_Type : in String) is begin if Length (Alternative) > 0 then Append (Message.Message, "Content-Type: multipart/alternative; boundary=AAA" & ASCII.LF & ASCII.LF); Append (Message.Message, "--AAA" & ASCII.LF); end if; Append (Message.Message, "Content-Type: "); Append (Message.Message, Content_Type); Append (Message.Message, ASCII.LF); Append (Message.Message, Content); if Length (Alternative) > 0 then Append (Message.Message, ASCII.LF & "--AAA" & ASCII.LF); Append (Message.Message, "Content-Type: text/plain; charset=utf-8" & ASCII.LF); Append (Message.Message, Alternative); Append (Message.Message, ASCII.LF & "--AAA" & ASCII.LF); end if; end Set_Body; -- ------------------------------ -- Add an attachment with the given content. -- ------------------------------ overriding procedure Add_Attachment (Message : in out File_Mail_Message; Content : in Unbounded_String; Content_Id : in String; Content_Type : in String) is begin Append (Message.Message, "Content-Type: "); Append (Message.Message, Content_Type); Append (Message.Message, "; boundary=BBB"); Append (Message.Message, ASCII.LF); if Content_Id'Length > 0 then Append (Message.Message, "Content-Id: "); Append (Message.Message, Content_Id); Append (Message.Message, ASCII.LF); end if; Append (Message.Message, "==BBB" & ASCII.LF); Append (Message.Message, Content); Append (Message.Message, "==BBB" & ASCII.LF); end Add_Attachment; -- ------------------------------ -- Add an attachment with the given content. -- ------------------------------ overriding procedure Add_File_Attachment (Message : in out File_Mail_Message; Filename : in String; Content_Id : in String; Content_Type : in String) is begin Append (Message.Message, "Content-Type: "); Append (Message.Message, Content_Type); Append (Message.Message, "; boundary=BBB"); Append (Message.Message, ASCII.LF); if Content_Id'Length > 0 then Append (Message.Message, "Content-Id: "); Append (Message.Message, Content_Id); Append (Message.Message, ASCII.LF); end if; Append (Message.Message, "==BBB" & ASCII.LF); Append (Message.Message, Filename); Append (Message.Message, "==BBB" & ASCII.LF); end Add_File_Attachment; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out File_Mail_Message) is N : Natural; Output : Ada.Text_IO.File_Type; begin Util.Concurrent.Counters.Increment (Message.Manager.Index, N); declare Path : constant String := Util.Files.Compose (To_String (Message.Manager.Path), "msg-" & Util.Strings.Image (N)); begin Log.Info ("Sending dumb mail to {0}", Path); Ada.Text_IO.Create (File => Output, Mode => Ada.Text_IO.Out_File, Name => Path); Ada.Text_IO.Put_Line (Output, To_String (Message.From)); if Length (Message.To) > 0 then Ada.Text_IO.Put_Line (Output, To_String (Message.To)); end if; if Length (Message.Cc) > 0 then Ada.Text_IO.Put_Line (Output, To_String (Message.Cc)); end if; if Length (Message.Bcc) > 0 then Ada.Text_IO.Put_Line (Output, To_String (Message.Bcc)); end if; Ada.Text_IO.Put (Output, "Subject: "); Ada.Text_IO.Put_Line (Output, To_String (Message.Subject)); Ada.Text_IO.Put_Line (Output, To_String (Message.Message)); Ada.Text_IO.Put_Line (Output, To_String (Message.Attachments)); Ada.Text_IO.Close (Output); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot create mail file {0}", Path); end; end Send; -- ------------------------------ -- Create a file based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Result : constant File_Mail_Manager_Access := new File_Mail_Manager; begin Result.Self := Result; Result.Path := To_Unbounded_String (Props.Get (NAME & ".maildir", "mail")); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in File_Mail_Manager) return Mail_Message_Access is Result : constant File_Mail_Message_Access := new File_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.Files;
Implement a simple Add_File_Attachment (for unit tests only)
Implement a simple Add_File_Attachment (for unit tests only)
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
285363cd48125d2560999f9130fc6794c320f2e5
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Strings; with ADO; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; with ASF.Helpers.Beans; with ASF.Tests; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with Security.Contexts; with AWA.Workspaces.Beans; package body AWA.Workspaces.Tests is use Ada.Strings.Unbounded; use AWA.Tests; function Get_Invitation_Bean is new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean, Element_Access => Beans.Invitation_Bean_Access); package Caller is new Util.Test_Caller (Test, "Workspaces.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send", Test_Invite_User'Access); Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Delete", Test_Delete_Member'Access); end Add_Tests; -- ------------------------------ -- Verify the anonymous access for the invitation page. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Key : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html"); ASF.Tests.Assert_Contains (T, "Bad or invalid invitation", Reply, "This invitation is invalid"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html"); ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply, "This invitation is invalid (key)"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key, "invitation-bad2.html"); ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply, "This invitation is invalid (key)"); if Key = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html"); ASF.Tests.Assert_Contains (T, "Accept invitation", Reply, "Accept invitation page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Test sending an invitation. -- ------------------------------ procedure Test_Invite_User (T : in out Test) is use type ADO.Identifier; use type AWA.Workspaces.Beans.Invitation_Bean_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Invite : AWA.Workspaces.Beans.Invitation_Bean_Access; Check : AWA.Workspaces.Beans.Invitation_Bean; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("message", "I invite you to this application"); Request.Set_Parameter ("send", "1"); Request.Set_Parameter ("invite", "1"); ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_TEMPORARY_REDIRECT, "Invalid response after invitation creation"); -- Verify the invitation by looking at the inviteUser bean. Invite := Get_Invitation_Bean (Request, "inviteUser"); T.Assert (Invite /= null, "Null inviteUser bean"); T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid"); T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null"); Check.Key := Invite.Get_Access_Key.Get_Access_Key; T.Verify_Anonymous (Invite.Get_Access_Key.Get_Access_Key); end Test_Invite_User; -- ------------------------------ -- Test deleting the member. -- ------------------------------ procedure Test_Delete_Member (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin T.Test_Invite_User; AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("member-id", ADO.Identifier'Image (T.Member_Id)); Request.Set_Parameter ("delete", "1"); Request.Set_Parameter ("delete-member-form", "1"); ASF.Tests.Do_Post (Request, Reply, "/workspaces/forms/delete-member.html", "delete-member.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response after delete member operation"); end Test_Delete_Member; end AWA.Workspaces.Tests;
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Strings; with ADO; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; with ASF.Helpers.Beans; with ASF.Tests; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with Security.Contexts; with AWA.Workspaces.Beans; package body AWA.Workspaces.Tests is use Ada.Strings.Unbounded; use AWA.Tests; function Get_Invitation_Bean is new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean, Element_Access => Beans.Invitation_Bean_Access); package Caller is new Util.Test_Caller (Test, "Workspaces.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send", Test_Invite_User'Access); Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Delete", Test_Delete_Member'Access); end Add_Tests; -- ------------------------------ -- Verify the anonymous access for the invitation page. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Key : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html"); ASF.Tests.Assert_Contains (T, "Bad or invalid invitation", Reply, "This invitation is invalid"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html"); ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply, "This invitation is invalid (key)"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key, "invitation-bad2.html"); ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply, "This invitation is invalid (key)"); if Key = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html"); ASF.Tests.Assert_Contains (T, "Accept invitation", Reply, "Accept invitation page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Test sending an invitation. -- ------------------------------ procedure Test_Invite_User (T : in out Test) is use type ADO.Identifier; use type AWA.Workspaces.Beans.Invitation_Bean_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Invite : AWA.Workspaces.Beans.Invitation_Bean_Access; Check : AWA.Workspaces.Beans.Invitation_Bean; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("message", "I invite you to this application"); Request.Set_Parameter ("send", "1"); Request.Set_Parameter ("invite", "1"); ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after invitation creation"); -- Verify the invitation by looking at the inviteUser bean. Invite := Get_Invitation_Bean (Request, "inviteUser"); T.Assert (Invite /= null, "Null inviteUser bean"); T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid"); T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null"); T.Assert (Invite.Get_Member.Is_Inserted, "The invitation has a workspace member"); Check.Key := Invite.Get_Access_Key.Get_Access_Key; T.Verify_Anonymous (Invite.Get_Access_Key.Get_Access_Key); T.Member_ID := Invite.Get_Member.Get_Id; end Test_Invite_User; -- ------------------------------ -- Test deleting the member. -- ------------------------------ procedure Test_Delete_Member (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin T.Test_Invite_User; AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("member-id", ADO.Identifier'Image (T.Member_Id)); Request.Set_Parameter ("delete", "1"); Request.Set_Parameter ("delete-member-form", "1"); ASF.Tests.Do_Post (Request, Reply, "/workspaces/forms/delete-member.html", "delete-member.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response after delete member operation"); ASF.Tests.Assert_Contains (T, "deleteDialog_" & ADO.Identifier'Image (T.Member_Id), Reply, "Delete member dialog operation response is invalid"); end Test_Delete_Member; end AWA.Workspaces.Tests;
Update the test for delete member to verify the response sent
Update the test for delete member to verify the response sent
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
aa36b30899e439da3ee2a697b8deec7c6df1f453
testutil/util-tests.ads
testutil/util-tests.ads
----------------------------------------------------------------------- -- AUnit utils - Helper for writing unit tests -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with GNAT.Source_Info; with Util.Properties; with Util.Assertions; with Util.XUnit; package Util.Tests is use Ada.Strings.Unbounded; subtype Message_String is Util.XUnit.Message_String; subtype Test_Case is Util.XUnit.Test_Case; subtype Test_Suite is Util.XUnit.Test_Suite; subtype Access_Test_Suite is Util.XUnit.Access_Test_Suite; function Format (S : in String) return Message_String renames Util.XUnit.Format; type Test is new Util.XUnit.Test with null record; -- Get a path to access a test file. function Get_Path (File : String) return String; -- Get a path to create a test file. function Get_Test_Path (File : String) return String; -- Get the timeout for the test execution. function Get_Test_Timeout (Name : in String) return Duration; -- Get the testsuite harness prefix. This prefix is added to the test class name. -- By default it is empty. It is allows to execute the test harness on different -- environment (ex: MySQL or SQLlite) and be able to merge and collect the two result -- sets together. function Get_Harness_Prefix return String; -- Get a test configuration parameter. function Get_Parameter (Name : String; Default : String := "") return String; -- Get the test configuration properties. function Get_Properties return Util.Properties.Manager; -- Get a new unique string function Get_Uuid return String; -- Check that two files are equal. This is intended to be used by -- tests that create files that are then checked against patterns. procedure Assert_Equal_Files (T : in Test_Case'Class; Expect : in String; Test : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals is new Assertions.Assert_Equals_T (Value_Type => Integer); procedure Assert_Equals is new Assertions.Assert_Equals_T (Value_Type => Character); -- Check that the value matches what we expect. -- procedure Assert (T : in Test'Class; -- Condition : in Boolean; -- Message : in String := "Test failed"; -- Source : String := GNAT.Source_Info.File; -- Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect, Value : in Ada.Calendar.Time; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect, Value : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect : in String; Value : in Unbounded_String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches the regular expression procedure Assert_Matches (T : in Test'Class; Pattern : in String; Value : in Unbounded_String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches the regular expression procedure Assert_Matches (T : in Test'Class; Pattern : in String; Value : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Default initialization procedure. procedure Initialize_Test (Props : in Util.Properties.Manager); -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. generic with function Suite return Access_Test_Suite; with procedure Initialize (Props : in Util.Properties.Manager) is Initialize_Test; procedure Harness (Name : in String); end Util.Tests;
----------------------------------------------------------------------- -- AUnit utils - Helper for writing unit tests -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with GNAT.Source_Info; with Util.Properties; with Util.Assertions; with Util.XUnit; package Util.Tests is use Ada.Strings.Unbounded; subtype Message_String is Util.XUnit.Message_String; subtype Test_Case is Util.XUnit.Test_Case; subtype Test_Suite is Util.XUnit.Test_Suite; subtype Access_Test_Suite is Util.XUnit.Access_Test_Suite; function Format (S : in String) return Message_String renames Util.XUnit.Format; type Test is new Util.XUnit.Test with null record; -- Get a path to access a test file. function Get_Path (File : String) return String; -- Get a path to create a test file. function Get_Test_Path (File : String) return String; -- Get the timeout for the test execution. function Get_Test_Timeout (Name : in String) return Duration; -- Get the testsuite harness prefix. This prefix is added to the test class name. -- By default it is empty. It is allows to execute the test harness on different -- environment (ex: MySQL or SQLlite) and be able to merge and collect the two result -- sets together. function Get_Harness_Prefix return String; -- Get a test configuration parameter. function Get_Parameter (Name : String; Default : String := "") return String; -- Get the test configuration properties. function Get_Properties return Util.Properties.Manager; -- Get a new unique string function Get_Uuid return String; -- Check that two files are equal. This is intended to be used by -- tests that create files that are then checked against patterns. procedure Assert_Equal_Files (T : in Test_Case'Class; Expect : in String; Test : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals is new Assertions.Assert_Equals_T (Value_Type => Integer); procedure Assert_Equals is new Assertions.Assert_Equals_T (Value_Type => Character); procedure Assert_Equals is new Assertions.Assert_Equals_T (Value_Type => Long_Long_Integer); -- Check that the value matches what we expect. -- procedure Assert (T : in Test'Class; -- Condition : in Boolean; -- Message : in String := "Test failed"; -- Source : String := GNAT.Source_Info.File; -- Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect, Value : in Ada.Calendar.Time; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect, Value : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect : in String; Value : in Unbounded_String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches the regular expression procedure Assert_Matches (T : in Test'Class; Pattern : in String; Value : in Unbounded_String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches the regular expression procedure Assert_Matches (T : in Test'Class; Pattern : in String; Value : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Default initialization procedure. procedure Initialize_Test (Props : in Util.Properties.Manager); -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. generic with function Suite return Access_Test_Suite; with procedure Initialize (Props : in Util.Properties.Manager) is Initialize_Test; procedure Harness (Name : in String); end Util.Tests;
Add an Assert_Equals on Long_Long_Integer type
Add an Assert_Equals on Long_Long_Integer type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b9f921f8e34dab2b14e38ff1f5d4c33c1afafe95
orka/src/orka/implementation/orka-loggers-formatting.adb
orka/src/orka/implementation/orka-loggers-formatting.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2019 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Strings.Fixed; with Orka.Terminals; package body Orka.Loggers.Formatting is package SF renames Ada.Strings.Fixed; Length_Level : constant := 7; function Format_Message (From : String; Level : Severity; Message : String; Colorize : Boolean) return String is Level_Color : constant Terminals.Color := (case Level is when Error => Terminals.Red, when Warning => Terminals.Yellow, when Failure => Terminals.Red, when Success => Terminals.Green, when Info => Terminals.Blue, when Debug => Terminals.Default); Level_Icon : constant String := (case Level is when Error => "", when Warning => "", when Failure => "", when Success => "", when Info => "", when Debug => " "); Level_Image : String (1 .. Length_Level); function Colorize_Text (Text : String; Color : Terminals.Color) return String is (if Colorize then Terminals.Colorize (Text, Color) else Text); begin SF.Move (Level'Image, Level_Image, Justify => Ada.Strings.Center); return Colorize_Text (Terminals.Time_Image, Terminals.Grey) & " " & Colorize_Text ("[" & Level_Icon & " " & Level_Image & "]", Level_Color) & " " & Colorize_Text ("[" & From & "]", Terminals.Magenta) & " " & Terminals.Strip_Line_Term (Message); end Format_Message; end Orka.Loggers.Formatting;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2019 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Strings.Fixed; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Orka.Terminals; package body Orka.Loggers.Formatting is package SF renames Ada.Strings.Fixed; package UTF renames Ada.Strings.UTF_Encoding; function Unicode (Number : Long_Integer) return UTF.UTF_8_String is (UTF.Wide_Wide_Strings.Encode ("" & Wide_Wide_Character'Val (Number))); Length_Level : constant := 7; function Format_Message (From : String; Level : Severity; Message : String; Colorize : Boolean) return String is Level_Color : constant Terminals.Color := (case Level is when Error => Terminals.Red, when Warning => Terminals.Yellow, when Failure => Terminals.Red, when Success => Terminals.Green, when Info => Terminals.Blue, when Debug => Terminals.Default); Level_Icon : constant UTF.UTF_8_String := (case Level is when Error => Unicode (16#F06A#), --  when Warning => Unicode (16#F071#), --  when Failure => Unicode (16#F05C#), --  when Success => Unicode (16#F05D#), --  when Info => Unicode (16#F05A#), --  when Debug => " "); -- Symbols from font FontAwesome Level_Image : String (1 .. Length_Level); function Colorize_Text (Text : String; Color : Terminals.Color) return String is (if Colorize then Terminals.Colorize (Text, Color) else Text); begin SF.Move (Level'Image, Level_Image, Justify => Ada.Strings.Center); return Colorize_Text (Terminals.Time_Image, Terminals.Grey) & " " & Colorize_Text ("[" & Level_Icon & " " & Level_Image & "]", Level_Color) & " " & Colorize_Text ("[" & From & "]", Terminals.Magenta) & " " & Terminals.Strip_Line_Term (Message); end Format_Message; end Orka.Loggers.Formatting;
Fix compilation when building using alr with UTF-8 support
orka: Fix compilation when building using alr with UTF-8 support The 'Val attribute is used because the symbols cannot be written as string literals because the symbols are from the private use area of font FontAwesome. Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
ddf0677243d5dfa0961dc6e12189bf87a1cf0b99
regtests/security-oauth-clients-tests.adb
regtests/security-oauth-clients-tests.adb
----------------------------------------------------------------------- -- Security-oauth-clients-tests - Unit tests for OAuth -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with Util.Strings.Sets; package body Security.OAuth.Clients.Tests is package Caller is new Util.Test_Caller (Test, "Security.OAuth.Clients"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Create_Nonce", Test_Create_Nonce'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Get_State", Test_Get_State'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Is_Valid_State", Test_Is_Valid_State'Access); end Add_Tests; -- ------------------------------ -- Test Create_Nonce operation. -- ------------------------------ procedure Test_Create_Nonce (T : in out Test) is Nonces : Util.Strings.Sets.Set; begin for I in 1 .. 1_000 loop for I in 32 .. 734 loop declare S : constant String := Create_Nonce (I * 3); begin T.Assert (not Nonces.Contains (S), "Nonce was not unique: " & S); Nonces.Include (S); end; end loop; end loop; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare Nonce : constant String := Create_Nonce (128); pragma Unreferenced (Nonce); begin null; end; end loop; Util.Measures.Report (S, "128 bits nonce generation (1000 calls)"); end; end Test_Create_Nonce; -- ------------------------------ -- Test the Get_State operation. -- ------------------------------ procedure Test_Get_State (T : in out Test) is App : Application; Nonce : constant String := Create_Nonce (128); begin App.Set_Application_Identifier ("test"); Util.Tests.Assert_Equals (T, "test", App.Get_Application_Identifier, "Invalid application"); App.Set_Application_Secret ("my-secret"); App.Set_Application_Callback ("my-callback"); App.Set_Provider_URI ("http://my-provider"); declare State : constant String := App.Get_State (Nonce); begin T.Assert (State'Length > 25, "State is too small: " & State); end; end Test_Get_State; -- ------------------------------ -- Test the Is_Valid_State operation. -- ------------------------------ procedure Test_Is_Valid_State (T : in out Test) is App : Application; begin App.Set_Application_Identifier ("test"); Util.Tests.Assert_Equals (T, "test", App.Get_Application_Identifier, "Invalid application"); App.Set_Application_Secret ("my-secret"); App.Set_Application_Callback ("my-callback"); App.Set_Provider_URI ("http://my-provider"); for I in 1 .. 100 loop declare Nonce : constant String := Create_Nonce (128); State : constant String := App.Get_State (Nonce); begin T.Assert (State'Length > 25, "State is too small: " & State); T.Assert (App.Is_Valid_State (Nonce, State), "Invalid state: " & State); T.Assert (not App.Is_Valid_State ("", State), "State was valid with invalid nonce"); T.Assert (not App.Is_Valid_State (State, State), "State must be invalid"); T.Assert (not App.Is_Valid_State (Nonce, State & "d"), "State must be invalid"); end; end loop; end Test_Is_Valid_State; end Security.OAuth.Clients.Tests;
----------------------------------------------------------------------- -- Security-oauth-clients-tests - Unit tests for OAuth -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Util.Test_Caller; with Util.Measures; with Util.Strings.Sets; package body Security.OAuth.Clients.Tests is package Caller is new Util.Test_Caller (Test, "Security.OAuth.Clients"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Create_Nonce", Test_Create_Nonce'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Get_State", Test_Get_State'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Clients.Is_Valid_State", Test_Is_Valid_State'Access); end Add_Tests; -- ------------------------------ -- Test Create_Nonce operation. -- ------------------------------ procedure Test_Create_Nonce (T : in out Test) is Nonces : Util.Strings.Sets.Set; begin for I in 1 .. 1_000 loop for I in 32 .. 734 loop declare S : constant String := Create_Nonce (I * 3); begin T.Assert (not Nonces.Contains (S), "Nonce was not unique: " & S); Nonces.Include (S); end; end loop; end loop; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare Nonce : constant String := Create_Nonce (128); pragma Unreferenced (Nonce); begin null; end; end loop; Util.Measures.Report (S, "128 bits nonce generation (1000 calls)"); end; end Test_Create_Nonce; -- ------------------------------ -- Test the Get_State operation. -- ------------------------------ procedure Test_Get_State (T : in out Test) is App : Application; Nonce : constant String := Create_Nonce (128); begin App.Set_Application_Identifier ("test"); Util.Tests.Assert_Equals (T, "test", App.Get_Application_Identifier, "Invalid application"); App.Set_Application_Secret ("my-secret"); App.Set_Application_Callback ("my-callback"); App.Set_Provider_URI ("http://my-provider"); declare State : constant String := App.Get_State (Nonce); begin T.Assert (State'Length > 25, "State is too small: " & State); T.Assert (Ada.Strings.Fixed.Index (State, Nonce) = 0, "The state must not contain the nonce"); -- Calling Get_State with the same nonce should produce the same result. Util.Tests.Assert_Equals (T, State, App.Get_State (Nonce), "Invalid state"); App.Set_Application_Secret ("second-secret"); declare State2 : constant String := App.Get_State (Nonce); begin T.Assert (State /= State2, "Changing the application key should produce a different state"); end; -- Restore the secret and change the callback. App.Set_Application_Secret ("my-secret"); App.Set_Application_Callback ("my-callback2"); declare State2 : constant String := App.Get_State (Nonce); begin T.Assert (State /= State2, "Changing the application callback should produce a different state"); end; -- Restore the callback and change the client Id. App.Set_Application_Callback ("my-callback"); App.Set_Application_Identifier ("test2"); declare State2 : constant String := App.Get_State (Nonce); begin T.Assert (State /= State2, "Changing the application identifier should produce a different state"); end; end; end Test_Get_State; -- ------------------------------ -- Test the Is_Valid_State operation. -- ------------------------------ procedure Test_Is_Valid_State (T : in out Test) is App : Application; begin App.Set_Application_Identifier ("test"); Util.Tests.Assert_Equals (T, "test", App.Get_Application_Identifier, "Invalid application"); App.Set_Application_Secret ("my-secret"); App.Set_Application_Callback ("my-callback"); App.Set_Provider_URI ("http://my-provider"); for I in 1 .. 100 loop declare Nonce : constant String := Create_Nonce (128); State : constant String := App.Get_State (Nonce); begin T.Assert (State'Length > 25, "State is too small: " & State); T.Assert (App.Is_Valid_State (Nonce, State), "Invalid state: " & State); T.Assert (not App.Is_Valid_State ("", State), "State was valid with invalid nonce"); T.Assert (not App.Is_Valid_State (State, State), "State must be invalid"); T.Assert (not App.Is_Valid_State (Nonce, State & "d"), "State must be invalid"); end; end loop; end Test_Is_Valid_State; end Security.OAuth.Clients.Tests;
Add more tests for the Get_State generation
Add more tests for the Get_State generation
Ada
apache-2.0
stcarrez/ada-security
84dbdefbee48cf2946dda02f372ec6838e5ebe42
mat/src/mat-targets-probes.adb
mat/src/mat-targets-probes.adb
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ELF; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes"); M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; M_LIBNAME : constant MAT.Events.Internal_Reference := 6; M_LADDR : constant MAT.Events.Internal_Reference := 7; M_COUNT : constant MAT.Events.Internal_Reference := 8; M_TYPE : constant MAT.Events.Internal_Reference := 9; M_VADDR : constant MAT.Events.Internal_Reference := 10; M_SIZE : constant MAT.Events.Internal_Reference := 11; M_FLAGS : constant MAT.Events.Internal_Reference := 12; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; LIBNAME_NAME : aliased constant String := "libname"; LADDR_NAME : aliased constant String := "laddr"; COUNT_NAME : aliased constant String := "count"; TYPE_NAME : aliased constant String := "type"; VADDR_NAME : aliased constant String := "vaddr"; SIZE_NAME : aliased constant String := "size"; FLAGS_NAME : aliased constant String := "flags"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); Library_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => LIBNAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME), 2 => (Name => LADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_LADDR), 3 => (Name => COUNT_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_COUNT), 4 => (Name => TYPE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_TYPE), 5 => (Name => VADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_VADDR), 6 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_SIZE), 7 => (Name => FLAGS_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FLAGS)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Event.Addr := Heap.Start_Addr; Event.Size := Heap.Size; Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); end Probe_Begin; -- ------------------------------ -- Extract the information from the 'library' event. -- ------------------------------ procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Types.Target_Addr; Count : MAT.Types.Target_Size := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; Addr : MAT.Types.Target_Addr; Pos : Natural := Defs'Last + 1; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_COUNT => Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); Pos := I + 1; exit; when M_LIBNAME => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_LADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Event.Addr := Addr; Event.Size := 0; for Region in 1 .. Count loop declare Region : MAT.Memory.Region_Info; Kind : ELF.Elf32_Word := 0; begin for I in Pos .. Defs'Last loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_VADDR => Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_TYPE => Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when M_FLAGS => Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; if Kind = ELF.PT_LOAD then Region.Start_Addr := Addr + Region.Start_Addr; Region.End_Addr := Region.Start_Addr + Region.Size; Region.Path := Path; Event.Size := Event.Size + Region.Size; Probe.Target.Process.Memory.Add_Region (Region); end if; end; end loop; end Probe_Library; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Events.Targets.Probe_Index_Type; begin if Event.Index = MAT.Events.Targets.MSG_BEGIN then Probe.Probe_Begin (Params.all, Msg, Event); elsif Event.Index = MAT.Events.Targets.MSG_LIBRARY then Probe.Probe_Library (Params.all, Msg, Event); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MAT.Events.Targets.MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MAT.Events.Targets.MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MAT.Events.Targets.MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
----------------------------------------------------------------------- -- 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); 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; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_COUNT => Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); Pos := I + 1; exit; when M_LIBNAME => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_LADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Event.Addr := Addr; Event.Size := 0; for Region in 1 .. Count loop declare Region : MAT.Memory.Region_Info; Kind : ELF.Elf32_Word := 0; begin for I in Pos .. Defs'Last loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_VADDR => Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_TYPE => Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when M_FLAGS => Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; if Kind = ELF.PT_LOAD then Region.Start_Addr := Addr + Region.Start_Addr; Region.End_Addr := Region.Start_Addr + Region.Size; Region.Path := Path; Event.Size := Event.Size + Region.Size; Probe.Target.Process.Memory.Add_Region (Region); end if; end; end loop; end Probe_Library; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Events.Targets.Probe_Index_Type; begin if Event.Index = MAT.Events.Targets.MSG_BEGIN then Probe.Probe_Begin (Params.all, Msg, Event); elsif Event.Index = MAT.Events.Targets.MSG_LIBRARY then Probe.Probe_Library (Params.all, Msg, Event); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MAT.Events.Targets.MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MAT.Events.Targets.MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MAT.Events.Targets.MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f4857fe442abd0795fd0a7f33c0bf6cdc68762e4
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with ASF.Tests; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with AWA.Tests.Helpers; with AWA.Tests.Helpers.Users; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Wikis.Modules.Tests is use ASF.Tests; use Util.Tests; package Caller is new Util.Test_Caller (Test, "Wikis.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space", Test_Create_Wiki_Space'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page", Test_Create_Wiki_Page'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content", Test_Create_Wiki_Content'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Wiki_Page", Test_Wiki_Page'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save", Test_Update_Page'Access); end Add_Tests; -- ------------------------------ -- Test creation of a wiki space. -- ------------------------------ procedure Test_Create_Wiki_Space (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; W2 : AWA.Wikis.Models.Wiki_Space_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Wikis.Modules.Get_Wiki_Module; T.Assert (T.Manager /= null, "There is no wiki manager"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); T.Assert (W.Is_Inserted, "The new wiki space was not created"); W.Set_Name ("Test wiki space update"); W.Set_Is_Public (True); T.Manager.Save_Wiki_Space (W); T.Manager.Load_Wiki_Space (Wiki => W2, Id => W.Get_Id); Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name), "Invalid wiki space name"); end Test_Create_Wiki_Space; -- ------------------------------ -- Test creation of a wiki page. -- ------------------------------ procedure Test_Create_Wiki_Page (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; P : AWA.Wikis.Models.Wiki_Page_Ref; C : AWA.Wikis.Models.Wiki_Content_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); P.Set_Name ("Private"); P.Set_Title ("The page title"); T.Manager.Create_Wiki_Page (W, P, C); T.Assert (P.Is_Inserted, "The new wiki page was not created"); C := AWA.Wikis.Models.Null_Wiki_Content; P := AWA.Wikis.Models.Null_Wiki_Page; P.Set_Name ("Public"); P.Set_Title ("The page title (public)"); P.Set_Is_Public (True); T.Manager.Create_Wiki_Page (W, P, C); T.Assert (P.Is_Inserted, "The new wiki page was not created"); T.Assert (P.Get_Is_Public, "The new wiki page is not public"); end Test_Create_Wiki_Page; -- ------------------------------ -- Test creation of a wiki page content. -- ------------------------------ procedure Test_Create_Wiki_Content (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; P : AWA.Wikis.Models.Wiki_Page_Ref; C : AWA.Wikis.Models.Wiki_Content_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); T.Wiki_Id := W.Get_Id; P.Set_Name ("PrivatePage"); P.Set_Title ("The page title"); P.Set_Is_Public (False); T.Manager.Create_Wiki_Page (W, P, C); T.Private_Id := P.Get_Id; C := AWA.Wikis.Models.Null_Wiki_Content; C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN); C.Set_Content ("-- Title" & ASCII.LF & "A paragraph"); C.Set_Save_Comment ("A first version"); T.Manager.Create_Wiki_Content (P, C); T.Assert (C.Is_Inserted, "The new wiki content was not created"); T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author"); T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page"); P := AWA.Wikis.Models.Null_Wiki_Page; C := AWA.Wikis.Models.Null_Wiki_Content; P.Set_Name ("PublicPage"); P.Set_Title ("The public page title"); P.Set_Is_Public (True); T.Manager.Create_Wiki_Page (W, P, C); T.Public_Id := P.Get_Id; C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN); C.Set_Content ("-- Title" & ASCII.LF & "A paragraph" & ASCII.LF & "[Link](http://mylink.com)" & ASCII.LF & "[Image](my-image.png)"); C.Set_Save_Comment ("A first version"); T.Manager.Create_Wiki_Content (P, C); T.Assert (C.Is_Inserted, "The new wiki content was not created"); T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author"); T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page"); end Test_Create_Wiki_Content; -- ------------------------------ -- Test getting the wiki page as well as info, history pages. -- ------------------------------ procedure Test_Wiki_Page (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id)); Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id)); begin ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PublicPage", "wiki-public-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage)"); Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage page returned", Status => ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident, "wiki-public-info-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage info)"); Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned", Status => ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, "/wikis/history/" & Ident & "/" & Pub_Ident, "wiki-public-history-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage history)"); Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned", Status => ASF.Responses.SC_OK); Request.Remove_Attribute ("wikiView"); ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PrivatePage", "wiki-private-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PrivatePage)"); Assert_Matches (T, ".*Protected Wiki Page.*", Reply, "Invalid PrivatePage page returned", Status => ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent", "wiki-list-recent-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent)"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent/grid", "wiki-list-grid-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent/grid)"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular", "wiki-list-popular-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular)"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular/grid", "wiki-list-popular-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular/grid)"); end Test_Wiki_Page; -- ------------------------------ -- Test updating the wiki page through a POST request. -- ------------------------------ procedure Test_Update_Page (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id)); Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id)); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("page-id", Pub_Ident); Request.Set_Parameter ("page-wiki-id", Ident); Request.Set_Parameter ("name", "NewPageName"); Request.Set_Parameter ("page-title", "New Page Title"); Request.Set_Parameter ("text", "== Title ==" & ASCII.LF & "A paragraph" & ASCII.LF & "[[http://mylink.com|Link]]" & ASCII.LF & "[[Image:my-image.png|My Picture]]" & ASCII.LF & "== Last header ==" & ASCII.LF); Request.Set_Parameter ("comment", "Update through test post simulation"); Request.Set_Parameter ("page-is-public", "TRUE"); Request.Set_Parameter ("wiki-format", "FORMAT_MEDIAWIKI"); Request.Set_Parameter ("qtags[1]", "Test-Tag"); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post", "1"); ASF.Tests.Do_Post (Request, Reply, "/wikis/edit/" & Ident & "/PublicPage", "update-wiki.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after wiki update"); declare Result : constant String := AWA.Tests.Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/"); begin Util.Tests.Assert_Equals (T, Ident & "/NewPageName", Result, "The page name was not updated"); ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Result, "wiki-public-2.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (NewPageName)"); Assert_Matches (T, ".*Last header.*", Reply, "Last header is present in the response", Status => ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident, "wiki-info-2.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (info NewPageName)"); Assert_Matches (T, ".*wiki-image-name.*my-image.png.*", Reply, "The info page must list the image", Status => ASF.Responses.SC_OK); end; end Test_Update_Page; end AWA.Wikis.Modules.Tests;
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with ASF.Tests; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with AWA.Tests.Helpers; with AWA.Tests.Helpers.Users; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Wikis.Modules.Tests is use ASF.Tests; use Util.Tests; package Caller is new Util.Test_Caller (Test, "Wikis.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space", Test_Create_Wiki_Space'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page", Test_Create_Wiki_Page'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content", Test_Create_Wiki_Content'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Wiki_Page", Test_Wiki_Page'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save", Test_Update_Page'Access); end Add_Tests; -- ------------------------------ -- Test creation of a wiki space. -- ------------------------------ procedure Test_Create_Wiki_Space (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; W2 : AWA.Wikis.Models.Wiki_Space_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Wikis.Modules.Get_Wiki_Module; T.Assert (T.Manager /= null, "There is no wiki manager"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); T.Assert (W.Is_Inserted, "The new wiki space was not created"); W.Set_Name ("Test wiki space update"); W.Set_Is_Public (True); T.Manager.Save_Wiki_Space (W); T.Manager.Load_Wiki_Space (Wiki => W2, Id => W.Get_Id); Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name), "Invalid wiki space name"); end Test_Create_Wiki_Space; -- ------------------------------ -- Test creation of a wiki page. -- ------------------------------ procedure Test_Create_Wiki_Page (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; P : AWA.Wikis.Models.Wiki_Page_Ref; C : AWA.Wikis.Models.Wiki_Content_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); P.Set_Name ("Private"); P.Set_Title ("The page title"); T.Manager.Create_Wiki_Page (W, P, C); T.Assert (P.Is_Inserted, "The new wiki page was not created"); C := AWA.Wikis.Models.Null_Wiki_Content; P := AWA.Wikis.Models.Null_Wiki_Page; P.Set_Name ("Public"); P.Set_Title ("The page title (public)"); P.Set_Is_Public (True); T.Manager.Create_Wiki_Page (W, P, C); T.Assert (P.Is_Inserted, "The new wiki page was not created"); T.Assert (P.Get_Is_Public, "The new wiki page is not public"); end Test_Create_Wiki_Page; -- ------------------------------ -- Test creation of a wiki page content. -- ------------------------------ procedure Test_Create_Wiki_Content (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; P : AWA.Wikis.Models.Wiki_Page_Ref; C : AWA.Wikis.Models.Wiki_Content_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); T.Wiki_Id := W.Get_Id; P.Set_Name ("PrivatePage"); P.Set_Title ("The page title"); P.Set_Is_Public (False); T.Manager.Create_Wiki_Page (W, P, C); T.Private_Id := P.Get_Id; C := AWA.Wikis.Models.Null_Wiki_Content; C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN); C.Set_Content ("-- Title" & ASCII.LF & "A paragraph"); C.Set_Save_Comment ("A first version"); T.Manager.Create_Wiki_Content (P, C); T.Assert (C.Is_Inserted, "The new wiki content was not created"); T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author"); T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page"); P := AWA.Wikis.Models.Null_Wiki_Page; C := AWA.Wikis.Models.Null_Wiki_Content; P.Set_Name ("PublicPage"); P.Set_Title ("The public page title"); P.Set_Is_Public (True); T.Manager.Create_Wiki_Page (W, P, C); T.Public_Id := P.Get_Id; C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN); C.Set_Content ("-- Title" & ASCII.LF & "A paragraph" & ASCII.LF & "[Link](http://mylink.com)" & ASCII.LF & "[Image](my-image.png)"); C.Set_Save_Comment ("A first version"); T.Manager.Create_Wiki_Content (P, C); T.Assert (C.Is_Inserted, "The new wiki content was not created"); T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author"); T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page"); end Test_Create_Wiki_Content; -- ------------------------------ -- Test getting the wiki page as well as info, history pages. -- ------------------------------ procedure Test_Wiki_Page (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id)); Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id)); begin ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PublicPage", "wiki-public-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage)"); Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage page returned", Status => ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident, "wiki-public-info-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage info)"); Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned", Status => ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, "/wikis/history/" & Ident & "/" & Pub_Ident, "wiki-public-history-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage history)"); Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned", Status => ASF.Responses.SC_OK); Request.Remove_Attribute ("wikiView"); ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PrivatePage", "wiki-private-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PrivatePage)"); Assert_Matches (T, ".*Protected Wiki Page.*", Reply, "Invalid PrivatePage page returned", Status => ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent", "wiki-list-recent-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent)"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent/grid", "wiki-list-grid-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent/grid)"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular", "wiki-list-popular-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular)"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular/grid", "wiki-list-popular-1.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular/grid)"); end Test_Wiki_Page; -- ------------------------------ -- Test updating the wiki page through a POST request. -- ------------------------------ procedure Test_Update_Page (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id)); Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id)); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("page-id", Pub_Ident); Request.Set_Parameter ("page-wiki-id", Ident); Request.Set_Parameter ("name", "NewPageName"); Request.Set_Parameter ("page-title", "New Page Title"); Request.Set_Parameter ("text", "== Title ==" & ASCII.LF & "A paragraph" & ASCII.LF & "[[http://mylink.com|Link]]" & ASCII.LF & "[[Image:my-image.png|My Picture]]" & ASCII.LF & "== Last header ==" & ASCII.LF); Request.Set_Parameter ("comment", "Update through test post simulation"); Request.Set_Parameter ("page-is-public", "TRUE"); Request.Set_Parameter ("wiki-format", "FORMAT_MEDIAWIKI"); Request.Set_Parameter ("qtags[1]", "Test-Tag"); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post", "1"); ASF.Tests.Do_Post (Request, Reply, "/wikis/edit/" & Ident & "/PublicPage", "update-wiki.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after wiki update"); declare Result : constant String := AWA.Tests.Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/"); begin Util.Tests.Assert_Equals (T, Ident & "/NewPageName", Result, "The page name was not updated"); ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Result, "wiki-public-2.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (NewPageName)"); Assert_Matches (T, ".*Last header.*", Reply, "Last header is present in the response", Status => ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident, "wiki-info-2.html"); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (info NewPageName)"); Assert_Matches (T, ".*wiki-image-name.*my-image.png.*", Reply, "The info page must list the image", Status => ASF.Responses.SC_OK); end; end Test_Update_Page; end AWA.Wikis.Modules.Tests;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
322393f29a7d1bae390cef18fbcac3a7a8711d62
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.ads
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.ads
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; package AWA.Wikis.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Manager : AWA.Wikis.Modules.Wiki_Module_Access; end record; -- Test creation of a wiki space. procedure Test_Create_Wiki_Space (T : in out Test); -- Test creation of a wiki page. procedure Test_Create_Wiki_Page (T : in out Test); end AWA.Wikis.Modules.Tests;
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; package AWA.Wikis.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Manager : AWA.Wikis.Modules.Wiki_Module_Access; end record; -- Test creation of a wiki space. procedure Test_Create_Wiki_Space (T : in out Test); -- Test creation of a wiki page. procedure Test_Create_Wiki_Page (T : in out Test); -- Test creation of a wiki page content. procedure Test_Create_Wiki_Content (T : in out Test); end AWA.Wikis.Modules.Tests;
Add the Test_Create_Wiki_Content unit test
Add the Test_Create_Wiki_Content unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
27a18ca1daee350085b9bd1b9f3afb9f7beacd5d
src/wiki-streams-text_io.adb
src/wiki-streams-text_io.adb
----------------------------------------------------------------------- -- wiki-streams-text_io -- Text_IO input output streams -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Wiki.Helpers; package body Wiki.Streams.Text_IO is -- ------------------------------ -- Open the file and prepare to read the input stream. -- ------------------------------ procedure Open (Stream : in out File_Input_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form); end Open; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Input_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Input_Stream) is begin Stream.Close; end Finalize; -- ------------------------------ -- Read one character from the input stream and return False to the <tt>Eof</tt> indicator. -- When there is no character to read, return True in the <tt>Eof</tt> indicator. -- ------------------------------ overriding procedure Read (Input : in out File_Input_Stream; Char : out Wiki.Strings.WChar; Eof : out Boolean) is Available : Boolean; begin Eof := False; Ada.Wide_Wide_Text_IO.Get_Immediate (Input.File, Char, Available); exception when Ada.IO_Exceptions.End_Error => Char := Wiki.Helpers.LF; Eof := True; end Read; -- ------------------------------ -- Open the file and prepare to write the output stream. -- ------------------------------ procedure Open (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Open; -- ------------------------------ -- Create the file and prepare to write the output stream. -- ------------------------------ procedure Create (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Create; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Output_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Write the string to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Content : in Wiki.Strings.WString) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Content); else Ada.Wide_Wide_Text_IO.Put (Content); end if; end Write; -- ------------------------------ -- Write a single character to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Char : in Wiki.Strings.WChar) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Char); else Ada.Wide_Wide_Text_IO.Put (Char); end if; end Write; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Output_Stream) is begin Stream.Close; end Finalize; end Wiki.Streams.Text_IO;
----------------------------------------------------------------------- -- wiki-streams-text_io -- Text_IO input output streams -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Wiki.Helpers; package body Wiki.Streams.Text_IO is -- ------------------------------ -- Open the file and prepare to read the input stream. -- ------------------------------ procedure Open (Stream : in out File_Input_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form); end Open; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Input_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Input_Stream) is begin Stream.Close; end Finalize; -- ------------------------------ -- Read the input stream and fill the `Into` buffer until either it is full or -- we reach the end of line. Returns in `Last` the last valid position in the -- `Into` buffer. When there is no character to read, return True in -- the `Eof` indicator. -- ------------------------------ overriding procedure Read (Input : in out File_Input_Stream; Into : in out Wiki.Strings.WString; Last : out Natural; Eof : out Boolean) is Available : Boolean; Pos : Natural := Into'First; Char : Wiki.Strings.WChar; begin Eof := False; while Pos <= Into'Last loop Ada.Wide_Wide_Text_IO.Get_Immediate (Input.File, Char, Available); Into (Pos) := Char; Pos := Pos + 1; exit when Char = Helpers.LF or Char = Helpers.CR; end loop; Last := Pos - 1; exception when Ada.IO_Exceptions.End_Error => Last := Pos - 1; Eof := True; end Read; -- ------------------------------ -- Open the file and prepare to write the output stream. -- ------------------------------ procedure Open (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Open; -- ------------------------------ -- Create the file and prepare to write the output stream. -- ------------------------------ procedure Create (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Create; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Output_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Write the string to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Content : in Wiki.Strings.WString) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Content); else Ada.Wide_Wide_Text_IO.Put (Content); end if; end Write; -- ------------------------------ -- Write a single character to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Char : in Wiki.Strings.WChar) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Char); else Ada.Wide_Wide_Text_IO.Put (Char); end if; end Write; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Output_Stream) is begin Stream.Close; end Finalize; end Wiki.Streams.Text_IO;
Update the Read procedure to read a complete line
Update the Read procedure to read a complete line
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b76e7c149f1e02b4879f2c9ca00f098ec4425f21
regtests/asf-applications-main-tests.adb
regtests/asf-applications-main-tests.adb
----------------------------------------------------------------------- -- asf-applications-main-tests - Unit tests for Applications -- Copyright (C) 2011, 2012, 2014, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Objects; with Ada.Unchecked_Deallocation; with EL.Contexts.Default; with ASF.Applications.Tests; with ASF.Applications.Main.Configs; with ASF.Requests.Mockup; package body ASF.Applications.Main.Tests is use Util.Tests; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access; package Caller is new Util.Test_Caller (Test, "Applications.Main"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Applications.Main.Read_Configuration", Test_Read_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create", Test_Create_Bean'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Load_Bundle", Test_Load_Bundle'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Register,Load_Bundle", Test_Bundle_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Get_Supported_Locales", Test_Locales'Access); end Add_Tests; -- ------------------------------ -- Initialize the test application -- ------------------------------ procedure Set_Up (T : in out Test) is Fact : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; begin T.App := new ASF.Applications.Main.Application; C.Copy (Util.Tests.Get_Properties); T.App.Initialize (C, Fact); T.App.Register ("layoutMsg", "layout"); end Set_Up; -- ------------------------------ -- Deletes the application object -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class, Name => ASF.Applications.Main.Application_Access); begin Free (T.App); end Tear_Down; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Applications.Tests.Form_Bean_Access := new Applications.Tests.Form_Bean; begin return Result.all'Access; end Create_Form_Bean; -- ------------------------------ -- Test creation of module -- ------------------------------ procedure Test_Read_Configuration (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("config/empty.xml"); begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); end Test_Read_Configuration; -- ------------------------------ -- Test creation of a module and registration in an application. -- ------------------------------ procedure Test_Create_Bean (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type); procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type) is Value : Util.Beans.Objects.Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Context : EL.Contexts.Default.Default_Context; begin T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Context => Context, Result => Bean, Scope => Scope); T.Assert (Kind = Scope, "Invalid scope for " & Name); T.Assert (Bean /= null, "Invalid bean object"); Value := Util.Beans.Objects.To_Object (Bean); T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean"); -- Special test for the sessionForm bean which is initialized by configuration properties if Name = "sessionForm" then T.Assert_Equals ("[email protected]", Util.Beans.Objects.To_String (Bean.Get_Value ("email")), "Session form not initialized"); end if; end Check; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-module.xml"); begin T.App.Register_Class ("ASF.Applications.Tests.Form_Bean", Create_Form_Bean'Access); ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); -- Check the 'regtests/config/test-module.xml' managed bean configuration. Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE); Check ("sessionForm", ASF.Beans.SESSION_SCOPE); Check ("requestForm", ASF.Beans.REQUEST_SCOPE); end Test_Create_Bean; -- ------------------------------ -- Test loading a resource bundle through the application. -- ------------------------------ procedure Test_Load_Bundle (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml"); Bundle : ASF.Locales.Bundle; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Load_Bundle (Name => "samples", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Equals (T, "Help", String '(Bundle.Get ("layout_help_label")), "Invalid bundle value"); T.App.Load_Bundle (Name => "asf", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Matches (T, ".*greater than.*", String '(Bundle.Get ("validators.length.maximum")), "Invalid bundle value"); end Test_Load_Bundle; -- ------------------------------ -- Test application configuration and registration of resource bundles. -- ------------------------------ procedure Test_Bundle_Configuration (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml"); Result : Util.Beans.Basic.Readonly_Bean_Access; Context : aliased ASF.Contexts.Faces.Faces_Context; Ctx : aliased EL.Contexts.Default.Default_Context; Scope : Scope_Type; begin Context.Set_ELContext (Ctx'Unchecked_Access); ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Set_Context (Context'Unchecked_Access); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("samplesMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The samplesMsg bundle was not created"); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("defaultMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The defaultMsg bundle was not created"); end Test_Bundle_Configuration; -- ------------------------------ -- Test locales. -- ------------------------------ procedure Test_Locales (T : in out Test) is use Util.Locales; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-locales.xml"); Req : aliased ASF.Requests.Mockup.Request; View : constant access Applications.Views.View_Handler'Class := T.App.Get_View_Handler; Context : aliased ASF.Contexts.Faces.Faces_Context; ELContext : aliased EL.Contexts.Default.Default_Context; Locale : Util.Locales.Locale; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (T.App.Get_Default_Locale), "Invalid default locale"); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Request (Req'Unchecked_Access); Req.Set_Header ("Accept-Language", "da, en-gb;q=0.3, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, en-gb, en;q=0.8, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, "en_GB", To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, fr;q=0.7, fr-fr;q=0.8"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, "fr_FR", To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, ru, it;q=0.8, de;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); end Test_Locales; end ASF.Applications.Main.Tests;
----------------------------------------------------------------------- -- asf-applications-main-tests - Unit tests for Applications -- Copyright (C) 2011, 2012, 2014, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Objects; with Ada.Unchecked_Deallocation; with EL.Contexts.Default; with ASF.Applications.Tests; with ASF.Applications.Main.Configs; with ASF.Requests.Mockup; package body ASF.Applications.Main.Tests is use Util.Tests; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access; package Caller is new Util.Test_Caller (Test, "Applications.Main"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Applications.Main.Read_Configuration", Test_Read_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create", Test_Create_Bean'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Load_Bundle", Test_Load_Bundle'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Register,Load_Bundle", Test_Bundle_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Get_Supported_Locales", Test_Locales'Access); end Add_Tests; -- ------------------------------ -- Initialize the test application -- ------------------------------ procedure Set_Up (T : in out Test) is Fact : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; begin T.App := new ASF.Applications.Main.Application; C.Copy (Util.Tests.Get_Properties); T.App.Initialize (C, Fact); T.App.Register ("layoutMsg", "layout"); end Set_Up; -- ------------------------------ -- Deletes the application object -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class, Name => ASF.Applications.Main.Application_Access); begin Free (T.App); end Tear_Down; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Applications.Tests.Form_Bean_Access := new Applications.Tests.Form_Bean; begin return Result.all'Access; end Create_Form_Bean; -- ------------------------------ -- Test creation of module -- ------------------------------ procedure Test_Read_Configuration (T : in out Test) is Path : constant String := Util.Tests.Get_Path ("config/empty.xml"); begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); end Test_Read_Configuration; -- ------------------------------ -- Test creation of a module and registration in an application. -- ------------------------------ procedure Test_Create_Bean (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type); procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type) is Value : Util.Beans.Objects.Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Context : EL.Contexts.Default.Default_Context; begin T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Context => Context, Result => Bean, Scope => Scope); T.Assert (Kind = Scope, "Invalid scope for " & Name); T.Assert (Bean /= null, "Invalid bean object"); Value := Util.Beans.Objects.To_Object (Bean); T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean"); -- Special test for the sessionForm bean which is initialized by configuration properties if Name = "sessionForm" then T.Assert_Equals ("[email protected]", Util.Beans.Objects.To_String (Bean.Get_Value ("email")), "Session form not initialized"); end if; end Check; Path : constant String := Util.Tests.Get_Path ("regtests/config/test-module.xml"); begin T.App.Register_Class ("ASF.Applications.Tests.Form_Bean", Create_Form_Bean'Access); ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); -- Check the 'regtests/config/test-module.xml' managed bean configuration. Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE); Check ("sessionForm", ASF.Beans.SESSION_SCOPE); Check ("requestForm", ASF.Beans.REQUEST_SCOPE); end Test_Create_Bean; -- ------------------------------ -- Test loading a resource bundle through the application. -- ------------------------------ procedure Test_Load_Bundle (T : in out Test) is Path : constant String := Util.Tests.Get_Path ("regtests/config/test-bundle.xml"); Bundle : ASF.Locales.Bundle; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Load_Bundle (Name => "samples", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Equals (T, "Help", String '(Bundle.Get ("layout_help_label")), "Invalid bundle value"); T.App.Load_Bundle (Name => "asf", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Matches (T, ".*greater than.*", String '(Bundle.Get ("validators.length.maximum")), "Invalid bundle value"); end Test_Load_Bundle; -- ------------------------------ -- Test application configuration and registration of resource bundles. -- ------------------------------ procedure Test_Bundle_Configuration (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Path : constant String := Util.Tests.Get_Path ("regtests/config/test-bundle.xml"); Result : Util.Beans.Basic.Readonly_Bean_Access; Context : aliased ASF.Contexts.Faces.Faces_Context; Ctx : aliased EL.Contexts.Default.Default_Context; Scope : Scope_Type; begin Context.Set_ELContext (Ctx'Unchecked_Access); ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Set_Context (Context'Unchecked_Access); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("samplesMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The samplesMsg bundle was not created"); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("defaultMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The defaultMsg bundle was not created"); end Test_Bundle_Configuration; -- ------------------------------ -- Test locales. -- ------------------------------ procedure Test_Locales (T : in out Test) is use Util.Locales; Path : constant String := Util.Tests.Get_Path ("regtests/config/test-locales.xml"); Req : aliased ASF.Requests.Mockup.Request; View : constant access Applications.Views.View_Handler'Class := T.App.Get_View_Handler; Context : aliased ASF.Contexts.Faces.Faces_Context; ELContext : aliased EL.Contexts.Default.Default_Context; Locale : Util.Locales.Locale; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (T.App.Get_Default_Locale), "Invalid default locale"); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Request (Req'Unchecked_Access); Req.Set_Header ("Accept-Language", "da, en-gb;q=0.3, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, en-gb, en;q=0.8, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, "en_GB", To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, fr;q=0.7, fr-fr;q=0.8"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, "fr_FR", To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, ru, it;q=0.8, de;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); end Test_Locales; end ASF.Applications.Main.Tests;
Fix wrong use of Util.Tests.Get_Test_Path and use Util.Tests.Get_Path instead
Fix wrong use of Util.Tests.Get_Test_Path and use Util.Tests.Get_Path instead
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
b995b3a909bc83fdeaa4f9378b79de42c768b39f
regtests/ado-queries-tests.adb
regtests/ado-queries-tests.adb
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with ADO.Drivers.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Drivers.Connections; Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, 0); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, 0); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end; if Mysql_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, 1); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index'"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is use ADO.Drivers.Connections; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Info : Query_Info_Ref.Ref; begin -- Configure and load the XML queries. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), True); T.Assert (not Simple_Query.Query.Query.Get.Is_Null, "The simple query was not loaded"); T.Assert (not Index_Query.Query.Query.Get.Is_Null, "The index query was not loaded"); Info := Simple_Query.Query.Query.Get; -- Re-configure but do not reload. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), False); T.Assert (Info.Value = Simple_Query.Query.Query.Get.Value, "The simple query instance was not changed"); -- Configure again and reload. The query info must have changed. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), True); T.Assert (Info.Value /= Simple_Query.Query.Query.Get.Value, "The simple query instance was not changed"); -- Due to the reference held by 'Info', it refers to the data loaded first. T.Assert (Length (Info.Value.Main_Query (0).SQL) > 0, "The old query is not valid"); end Test_Initialize; end ADO.Queries.Tests;
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- 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 Util.Test_Caller; with Util.Properties; with ADO.Drivers.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Drivers.Connections; Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, 0); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, 0); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end; if Mysql_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Mysql_Driver.Get_Driver_Index); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index' (MySQL driver)"); end; end if; if Sqlite_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Sqlite_Driver.Get_Driver_Index); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index' (SQLite driver)"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is use ADO.Drivers.Connections; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Info : Query_Info_Ref.Ref; begin -- Configure and load the XML queries. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), True); T.Assert (not Simple_Query.Query.Query.Get.Is_Null, "The simple query was not loaded"); T.Assert (not Index_Query.Query.Query.Get.Is_Null, "The index query was not loaded"); Info := Simple_Query.Query.Query.Get; -- Re-configure but do not reload. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), False); T.Assert (Info.Value = Simple_Query.Query.Query.Get.Value, "The simple query instance was not changed"); -- Configure again and reload. The query info must have changed. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), True); T.Assert (Info.Value /= Simple_Query.Query.Query.Get.Value, "The simple query instance was not changed"); -- Due to the reference held by 'Info', it refers to the data loaded first. T.Assert (Length (Info.Value.Main_Query (0).SQL) > 0, "The old query is not valid"); end Test_Initialize; end ADO.Queries.Tests;
Fix the load query unit test
Fix the load query unit test
Ada
apache-2.0
Letractively/ada-ado
8dabddce5b4fd8769f44e996f8feb9680377714d
regtests/util-properties-tests.ads
regtests/util-properties-tests.ads
----------------------------------------------------------------------- -- Util -- Utilities -- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Properties.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Property (T : in out Test); procedure Test_Integer_Property (T : in out Test); procedure Test_Load_Property (T : in out Test); procedure Test_Load_Strip_Property (T : in out Test); procedure Test_Copy_Property (T : in out Test); procedure Test_Set_Preserve_Original (T : in out Test); procedure Test_Remove_Preserve_Original (T : in out Test); procedure Test_Missing_Property (T : in out Test); procedure Test_Load_Ini_Property (T : in out Test); procedure Test_Save_Properties (T : in out Test); end Util.Properties.Tests;
----------------------------------------------------------------------- -- util-properties-tests -- Tests for properties -- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Properties.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Property (T : in out Test); procedure Test_Integer_Property (T : in out Test); procedure Test_Load_Property (T : in out Test); procedure Test_Load_Strip_Property (T : in out Test); procedure Test_Copy_Property (T : in out Test); procedure Test_Set_Preserve_Original (T : in out Test); procedure Test_Remove_Preserve_Original (T : in out Test); procedure Test_Missing_Property (T : in out Test); procedure Test_Load_Ini_Property (T : in out Test); procedure Test_Save_Properties (T : in out Test); procedure Test_Remove_Property (T : in out Test); end Util.Properties.Tests;
Declare the Test_Remove_Property procedure to check the Remove
Declare the Test_Remove_Property procedure to check the Remove
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ca5a800ef7a495df52a02bf3dded94b81b7ac2f6
mat/src/mat-readers-streams.adb
mat/src/mat-readers-streams.adb
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.IO_Exceptions; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Read a message from the stream. -- ------------------------------ overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message) is use type Ada.Streams.Stream_Element_Offset; Buffer : constant Util.Streams.Buffered.Buffer_Access := Msg.Buffer.Buffer; Last : Ada.Streams.Stream_Element_Offset; begin Reader.Stream.Read (Buffer (0 .. 1), Last); if Last /= 2 then raise Ada.IO_Exceptions.End_Error; end if; Msg.Buffer.Size := 2; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Buffer'Last then Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size)); raise Ada.IO_Exceptions.Data_Error; end if; Reader.Stream.Read (Buffer (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Buffer (Last)'Address; Msg.Buffer.Size := Msg.Size; Log.Debug ("Read message size {0}", Natural'Image (Msg.Size)); end Read_Message; -- ------------------------------ -- Read the events from the stream and stop when the end of the stream is reached. -- ------------------------------ procedure Read_All (Reader : in out Stream_Reader_Type) is use Ada.Streams; use type MAT.Types.Uint8; Buffer : aliased Buffer_Type; Msg : Message; Last : Ada.Streams.Stream_Element_Offset; Format : MAT.Types.Uint8; begin Reader.Data := new Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE); Msg.Buffer := Buffer'Unchecked_Access; Msg.Buffer.Start := Reader.Data (0)'Address; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Reader.Data (MAX_MSG_SIZE)'Address; Buffer.Buffer := Reader.Data; Reader.Stream.Read (Reader.Data (0 .. 0), Last); Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); if Format = 0 then Msg.Buffer.Endian := LITTLE_ENDIAN; Log.Debug ("Data stream is little endian"); else Msg.Buffer.Endian := BIG_ENDIAN; Log.Debug ("Data stream is big endian"); end if; Reader.Read_Message (Msg); Reader.Read_Headers (Msg); while not Reader.Stream.Is_Eof loop Reader.Read_Message (Msg); Reader.Dispatch_Message (Msg); end loop; exception when Ada.IO_Exceptions.End_Error => null; end Read_All; end MAT.Readers.Streams;
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.IO_Exceptions; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Read a message from the stream. -- ------------------------------ overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message) is use type Ada.Streams.Stream_Element_Offset; Buffer : constant Util.Streams.Buffered.Buffer_Access := Msg.Buffer.Buffer; Last : Ada.Streams.Stream_Element_Offset; begin Reader.Stream.Read (Buffer (0 .. 1), Last); if Last /= 2 then raise Ada.IO_Exceptions.End_Error; end if; Msg.Buffer.Size := 2; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Buffer'Last then Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size)); raise Ada.IO_Exceptions.Data_Error; end if; Reader.Stream.Read (Buffer (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Buffer (Last)'Address; Msg.Buffer.Size := Msg.Size; Log.Debug ("Read message size {0}", Natural'Image (Msg.Size)); end Read_Message; -- ------------------------------ -- Read the events from the stream and stop when the end of the stream is reached. -- ------------------------------ procedure Read_All (Reader : in out Stream_Reader_Type) is use Ada.Streams; use type MAT.Types.Uint8; Buffer : aliased Buffer_Type; Msg : Message; Last : Ada.Streams.Stream_Element_Offset; Format : MAT.Types.Uint8; begin Reader.Data := new Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE); Msg.Buffer := Buffer'Unchecked_Access; Msg.Buffer.Start := Reader.Data (0)'Address; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Reader.Data (MAX_MSG_SIZE)'Address; Msg.Buffer.Size := 1; Buffer.Buffer := Reader.Data; Reader.Stream.Read (Reader.Data (0 .. 0), Last); Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); if Format = 0 then Msg.Buffer.Endian := LITTLE_ENDIAN; Log.Debug ("Data stream is little endian"); else Msg.Buffer.Endian := BIG_ENDIAN; Log.Debug ("Data stream is big endian"); end if; Reader.Read_Message (Msg); Reader.Read_Headers (Msg); while not Reader.Stream.Is_Eof loop Reader.Read_Message (Msg); Reader.Dispatch_Message (Msg); end loop; exception when Ada.IO_Exceptions.End_Error => null; end Read_All; end MAT.Readers.Streams;
Fix initialization of message to retrieve the event stream format
Fix initialization of message to retrieve the event stream format
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
73dd580da079710fbbaa0f62f368b423d918c362
awa/regtests/awa-blogs-services-tests.adb
awa/regtests/awa-blogs-services-tests.adb
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with Util.Measures; with ADO; with ADO.Sessions; with ADO.SQL; with ADO.Objects; with Ada.Calendar; with Security.Contexts; with AWA.Services.Contexts; with AWA.Blogs.Module; with AWA.Users.Services.Tests.Helpers; package body AWA.Blogs.Services.Tests is use Util.Tests; use ADO; use ADO.Objects; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog", Test_Create_Blog'Access); end Add_Tests; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Manager : AWA.Blogs.Services.Blog_Service_Access; Blog_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Users.Services.Tests.Helpers.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Module.Get_Blog_Manager; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog", Result => Blog_Id); end Test_Create_Blog; end AWA.Blogs.Services.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with Util.Measures; with ADO; with ADO.Sessions; with ADO.SQL; with ADO.Objects; with Ada.Calendar; with Security.Contexts; with AWA.Services.Contexts; with AWA.Blogs.Module; with AWA.Users.Services.Tests.Helpers; package body AWA.Blogs.Services.Tests is use Util.Tests; use ADO; use ADO.Objects; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post", Test_Create_Post'Access); end Add_Tests; -- ------------------------------ -- Test creation of a blog -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Manager : AWA.Blogs.Services.Blog_Service_Access; Blog_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Users.Services.Tests.Helpers.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Module.Get_Blog_Manager; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); end Test_Create_Blog; -- ------------------------------ -- Test creating and updating of a blog post -- ------------------------------ procedure Test_Create_Post (T : in out Test) is Manager : AWA.Blogs.Services.Blog_Service_Access; Blog_Id : ADO.Identifier; Post_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Users.Services.Tests.Helpers.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Module.Get_Blog_Manager; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog post", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); Manager.Create_Post (Blog_Id => Blog_Id, Title => "Testing blog title", URI => "testing-blog-title", Text => "The blog content", Result => Post_Id); T.Assert (Post_Id > 0, "Invalid post identifier"); Manager.Update_Post (Post_Id => Post_Id, Title => "New blog post title", Text => "The new post content"); Manager.Delete_Post (Post_Id => Post_Id); -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Update_Post (Post_Id => Post_Id, Title => "Something", Text => "Content"); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Delete_Post (Post_Id => Post_Id); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; end Test_Create_Post; end AWA.Blogs.Services.Tests;
Add unit test for post creation
Add unit test for post creation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
10d9b794e373aebffa137759835ee61972b48e37
awa/plugins/awa-questions/src/awa-questions-beans.adb
awa/plugins/awa-questions/src/awa-questions-beans.adb
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with AWA.Tags.Modules; with AWA.Services.Contexts; package body AWA.Questions.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tags" then return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Service.Load_Question (From, Id); From.Tags.Load_Tags (DB, Id); end; end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Question (Bean); Bean.Tags.Update_Tags (Bean.Get_Id); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); Object.Tags.Set_Permission ("question-edit"); return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Answer (From, From.Question, ADO.Utils.To_Identifier (Value)); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Answer (Answer => Bean); end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Questions.Models.Question_Info_List_Bean (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "tag" then From.Tag := Util.Beans.Objects.To_Unbounded_String (Value); From.Load_List; end if; end Set_Value; -- ------------------------------ -- Load the list of question. If a tag was set, filter the list of questions with the tag. -- ------------------------------ procedure Load_List (Into : in out Question_List_Bean) is use AWA.Questions.Models; use AWA.Services; use type ADO.Identifier; Session : ADO.Sessions.Session := Into.Service.Get_Session; Query : ADO.Queries.Context; Tag_Id : ADO.Identifier; begin AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id); if Tag_Id /= ADO.NO_IDENTIFIER then Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List); Query.Bind_Param (Name => "tag", Value => Tag_Id); else Query.Set_Query (AWA.Questions.Models.Query_Question_List); end if; ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Into, Session, Query); end Load_List; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_List_Bean_Access := new Question_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Object.Service := Module; Query.Set_Query (AWA.Questions.Models.Query_Question_List); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "tags" then return Util.Beans.Objects.To_Object (Value => From.Tags_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare package ASC renames AWA.Services.Contexts; use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; Ctx : constant ASC.Service_Context_Access := ASC.Current; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Id); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.ANSWER_TABLE, Session => Session); Query.Set_Query (AWA.Questions.Models.Query_Answer_List); AWA.Questions.Models.List (From.Answer_List, Session, Query); -- Load the tags if any. From.Tags.Load_Tags (Session, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with Util.Beans.Lists.Strings; with AWA.Tags.Modules; with AWA.Services.Contexts; package body AWA.Questions.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tags" then return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Service.Load_Question (From, Id); From.Tags.Load_Tags (DB, Id); end; end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Question (Bean); Bean.Tags.Update_Tags (Bean.Get_Id); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); Object.Tags.Set_Permission ("question-edit"); return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Answer (From, From.Question, ADO.Utils.To_Identifier (Value)); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Answer (Answer => Bean); end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_List_Bean; Name : in String) return Util.Beans.Objects.Object is Pos : Natural; begin if Name = "tags" then Pos := From.Questions.Get_Row_Index; if Pos = 0 then return Util.Beans.Objects.Null_Object; end if; declare Item : constant Models.Question_Info := From.Questions.List.Element (Pos); begin return From.Tags.Get_Tags (Item.Id); end; elsif Name = "questions" then return Util.Beans.Objects.To_Object (Value => From.Questions_Bean, Storage => Util.Beans.Objects.STATIC); else return From.Questions.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "tag" then From.Tag := Util.Beans.Objects.To_Unbounded_String (Value); From.Load_List; end if; end Set_Value; -- ------------------------------ -- Load the list of question. If a tag was set, filter the list of questions with the tag. -- ------------------------------ procedure Load_List (Into : in out Question_List_Bean) is use AWA.Questions.Models; use AWA.Services; use type ADO.Identifier; Session : ADO.Sessions.Session := Into.Service.Get_Session; Query : ADO.Queries.Context; Tag_Id : ADO.Identifier; begin AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id); if Tag_Id /= ADO.NO_IDENTIFIER then Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List); Query.Bind_Param (Name => "tag", Value => Tag_Id); else Query.Set_Query (AWA.Questions.Models.Query_Question_List); end if; ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Into.Questions, Session, Query); declare List : ADO.Utils.Identifier_Vector; Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First; begin while Question_Info_Vectors.Has_Element (Iter) loop List.Append (Question_Info_Vectors.Element (Iter).Id); Question_Info_Vectors.Next (Iter); end loop; Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all, List); end; end Load_List; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_List_Bean_Access := new Question_List_Bean; -- Session : ADO.Sessions.Session := Module.Get_Session; -- Query : ADO.Queries.Context; begin Object.Service := Module; Object.Questions_Bean := Object.Questions'Unchecked_Access; -- Query.Set_Query (AWA.Questions.Models.Query_Question_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "entity_type", -- Table => AWA.Questions.Models.QUESTION_TABLE, -- Session => Session); -- AWA.Questions.Models.List (Object.Questions, Session, Query); Object.Load_List; return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "tags" then return Util.Beans.Objects.To_Object (Value => From.Tags_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare package ASC renames AWA.Services.Contexts; use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; Ctx : constant ASC.Service_Context_Access := ASC.Current; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Id); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.ANSWER_TABLE, Session => Session); Query.Set_Query (AWA.Questions.Models.Query_Answer_List); AWA.Questions.Models.List (From.Answer_List, Session, Query); -- Load the tags if any. From.Tags.Load_Tags (Session, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
Load the tags associated with the list of question being displayed Return the tags associated with the current question when iterating over the list of questions
Load the tags associated with the list of question being displayed Return the tags associated with the current question when iterating over the list of questions
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
491448ecb283fc18a1210a72a29cde52f11fe39b
examples/shared/serial_ports/src/serial_io-nonblocking.ads
examples/shared/serial_ports/src/serial_io-nonblocking.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-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. -- -- -- ------------------------------------------------------------------------------ -- This package defines an abstract data type for a "serial port" providing -- non-blocking input (Get) and output (Put) procedures. The procedures are -- considered non-blocking because they return to the caller (potentially) -- before the entire message is received or sent. -- -- The serial port abstraction is a wrapper around a USART peripheral, -- described by a value of type Peripheral_Descriptor. -- -- Interrupts are used to send and receive characters. -- -- NB: clients must not send or receive messages until any prior sending or -- receiving is completed. See the two functions Sending and Receiving and -- the preconditions on Put and Get. with Message_Buffers; use Message_Buffers; with Ada.Interrupts; use Ada.Interrupts; package Serial_IO.Nonblocking is pragma Elaborate_Body; type Serial_Port (IRQ : Interrupt_ID; Device : not null access Peripheral_Descriptor) is tagged limited private; procedure Initialize (This : in out Serial_Port) with Post => Initialized (This); function Initialized (This : Serial_Port) return Boolean with Inline; Serial_Port_Uninitialized : exception; procedure Configure (This : in out Serial_Port; Baud_Rate : Baud_Rates; Parity : Parities := No_Parity; Data_Bits : Word_Lengths := Word_Length_8; End_Bits : Stop_Bits := Stopbits_1; Control : Flow_Control := No_Flow_Control) with Pre => (Initialized (This) or else raise Serial_Port_Uninitialized); procedure Put (This : in out Serial_Port; Msg : not null access Message) with Pre => (Initialized (This) or else raise Serial_Port_Uninitialized) and then not Sending (This), Inline; procedure Get (This : in out Serial_Port; Msg : not null access Message) with Pre => (Initialized (This) or else raise Serial_Port_Uninitialized) and then not Receiving (This), Inline; function Sending (This : in out Serial_Port) return Boolean; -- Returns whether This is currently sending a message. function Receiving (This : in out Serial_Port) return Boolean; -- Returns whether This is currently receiving a message. private -- The protected type defining the interrupt handling for sending and -- receiving characters via the USART attached to the serial port. Each -- serial port type a component of this protected type. protected type Controller (IRQ : Interrupt_ID; Port : access Serial_Port) is pragma Interrupt_Priority; procedure Start_Sending (Msg : not null access Message) with Pre => not Sending; procedure Start_Receiving (Msg : not null access Message) with Pre => not Receiving; function Sending return Boolean; function Receiving return Boolean; private Next_Out : Positive; Awaiting_Transfer : Natural; Outgoing_Msg : access Message; Incoming_Msg : access Message; procedure Handle_Transmission with Inline; procedure Handle_Reception with Inline; procedure Detect_Errors (Is_Xmit_IRQ : Boolean) with Inline; procedure IRQ_Handler with Attach_Handler => IRQ; end Controller; type Serial_Port (IRQ : Interrupt_ID; Device : not null access Peripheral_Descriptor) is tagged limited record Initialized : Boolean := False; Control : Controller (IRQ, Serial_Port'Access); end record; end Serial_IO.Nonblocking;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-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. -- -- -- ------------------------------------------------------------------------------ -- This package defines an abstract data type for a "serial port" providing -- non-blocking input (Get) and output (Put) procedures. The procedures are -- considered non-blocking because they return to the caller (potentially) -- before the entire message is received or sent. -- -- The serial port abstraction is a wrapper around a USART peripheral, -- described by a value of type Peripheral_Descriptor. -- -- Interrupts are used to send and receive characters. -- -- NB: clients must not send or receive messages until any prior sending or -- receiving is completed. See the two functions Sending and Receiving and -- the preconditions on Put and Get. with Message_Buffers; use Message_Buffers; with Ada.Interrupts; use Ada.Interrupts; package Serial_IO.Nonblocking is pragma Elaborate_Body; type Serial_Port (IRQ : Interrupt_ID; Device : not null access Peripheral_Descriptor) is tagged limited private; procedure Initialize (This : in out Serial_Port) with Post => Initialized (This); function Initialized (This : Serial_Port) return Boolean with Inline; Serial_Port_Uninitialized : exception; procedure Configure (This : in out Serial_Port; Baud_Rate : Baud_Rates; Parity : Parities := No_Parity; Data_Bits : Word_Lengths := Word_Length_8; End_Bits : Stop_Bits := Stopbits_1; Control : Flow_Control := No_Flow_Control) with Pre => (Initialized (This) or else raise Serial_Port_Uninitialized); procedure Put (This : in out Serial_Port; Msg : not null access Message) with Pre => (Initialized (This) or else raise Serial_Port_Uninitialized) and then not Sending (This), Inline; procedure Get (This : in out Serial_Port; Msg : not null access Message) with Pre => (Initialized (This) or else raise Serial_Port_Uninitialized) and then not Receiving (This), Inline; function Sending (This : in out Serial_Port) return Boolean; -- Returns whether This is currently sending a message. function Receiving (This : in out Serial_Port) return Boolean; -- Returns whether This is currently receiving a message. private -- The protected type defining the interrupt handling for sending and -- receiving characters via the USART attached to the serial port. Each -- serial port type a component of this protected type. protected type Controller (IRQ : Interrupt_ID; Port : access Serial_Port) is pragma Interrupt_Priority; procedure Start_Sending (Msg : not null access Message); -- error: internal call cannot appear in precondition of protected operation -- with Pre => not Sending; procedure Start_Receiving (Msg : not null access Message); -- error: internal call cannot appear in precondition of protected operation -- with Pre => not Receiving; function Sending return Boolean; function Receiving return Boolean; private Next_Out : Positive; Awaiting_Transfer : Natural; Outgoing_Msg : access Message; Incoming_Msg : access Message; procedure Handle_Transmission with Inline; procedure Handle_Reception with Inline; procedure Detect_Errors (Is_Xmit_IRQ : Boolean) with Inline; procedure IRQ_Handler with Attach_Handler => IRQ; end Controller; type Serial_Port (IRQ : Interrupt_ID; Device : not null access Peripheral_Descriptor) is tagged limited record Initialized : Boolean := False; Control : Controller (IRQ, Serial_Port'Access); end record; end Serial_IO.Nonblocking;
Fix build error about PO contracts
serial_io-nonblocking.ads: Fix build error about PO contracts I didn't investigate at all.
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
dfaebbc1a5c6bc3dcaf04e2c438581343956e01a
components/src/motion/pmw3901/pmw3901.adb
components/src/motion/pmw3901/pmw3901.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2020, AdaCore -- -- Copyright (C) 2020, Simon Wright ([email protected]) -- -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ -- The algorithms used here are derived from Pimoroni's code at -- https://github.com/pimoroni/pmw3901-python. with Ada.Unchecked_Conversion; package body PMW3901 is -- Some registers Reg_ID : constant := 16#00#; Reg_ID_Inverted : constant := 16#5f#; Reg_Data_Ready : constant := 16#02#; Reg_Motion_Burst : constant := 16#16#; Reg_Power_Up_Reset : constant := 16#3a#; -- Reg_Orientation : constant := 16#5b#; Power_Up_Reset_Key : constant := 16#5a#; function Read (This : in out PMW3901_Flow_Sensor; Register : HAL.UInt8) return HAL.UInt8; procedure Write (This : in out PMW3901_Flow_Sensor; Register : HAL.UInt8; Value : HAL.UInt8); -------------- -- Is_Valid -- -------------- function Is_Valid (M : Motion) return Boolean is use type HAL.UInt8; begin return M.Motion_Occurred and not (M.S_Qual < 19 and M.Shutter_Upper = 16#1f#); end Is_Valid; ---------------- -- Initialize -- ---------------- procedure Initialize (This : in out PMW3901_Flow_Sensor) is begin This.CS.Clear; This.Timing.Delay_Milliseconds (50); This.CS.Set; declare Chip_ID : HAL.UInt8; Revision : HAL.UInt8; Inverted_Chip_ID : HAL.UInt8; use type HAL.UInt8; begin Chip_ID := Read (This, Reg_ID); Revision := Read (This, Reg_ID + 1); Inverted_Chip_ID := Read (This, Reg_ID_Inverted); if Chip_ID /= 16#49# or Revision /= 16#00# or Inverted_Chip_ID /= 16#b6# then -- Can't initialize the wrong sort of chip! raise SPI_Error with "no PMW3901 found"; end if; end; Write (This, Reg_Power_Up_Reset, Power_Up_Reset_Key); This.Timing.Delay_Milliseconds (20); -- Read the registers once declare Buff : HAL.SPI.SPI_Data_8b (0 .. 4); use type HAL.UInt8; begin for J in Buff'Range loop Buff (J) := Read (This, Reg_Data_Ready + HAL.UInt8 (J)); end loop; end; This.Initialized := True; end Initialize; --------------- -- Calibrate -- --------------- procedure Calibrate (This : in out PMW3901_Flow_Sensor) is type Magic is record Register : HAL.UInt8; Value : HAL.UInt8; end record; type Magics is array (Natural range <>) of Magic; procedure Write_Magics (Data : Magics); procedure Write_Magics (Data : Magics) is begin for J in Data'Range loop Write (This, Data (J).Register, Data (J).Value); end loop; end Write_Magics; use type HAL.UInt8; begin Write_Magics (((16#7f#, 16#00#), (16#55#, 16#01#), (16#50#, 16#07#), (16#7f#, 16#0e#), (16#43#, 16#10#))); declare Check : constant HAL.UInt8 := Read (This, 16#67#); begin if (Check and 2#1000_0000#) /= 0 then Write (This, 16#48#, 16#04#); else Write (This, 16#48#, 16#02#); end if; end; if Read (This, 16#73#) = 0 then declare C1, C2 : HAL.UInt8; begin C1 := Read (This, 16#70#); C2 := Read (This, 16#71#); if C1 <= 28 then C1 := C1 + 14; end if; if C1 > 28 then C1 := C1 + 11; end if; C2 := (C2 * 45) / 100; Write_Magics (((16#7f#, 16#00#), (16#51#, 16#7b#), (16#50#, 16#00#), (16#55#, 16#00#), (16#7f#, 16#0E#), (16#70#, C1), (16#71#, C2))); end; end if; Write_Magics (((16#7f#, 16#00#), (16#61#, 16#ad#), (16#7f#, 16#03#), (16#40#, 16#00#), (16#7f#, 16#05#), (16#41#, 16#b3#), (16#43#, 16#f1#), (16#45#, 16#14#), (16#5b#, 16#32#), (16#5f#, 16#34#), (16#7b#, 16#08#), (16#7f#, 16#06#), (16#44#, 16#1b#), (16#40#, 16#bf#), (16#4e#, 16#3f#), (16#7f#, 16#08#), (16#65#, 16#20#), (16#6a#, 16#18#), (16#7f#, 16#09#), (16#4f#, 16#af#), (16#5f#, 16#40#), (16#48#, 16#80#), (16#49#, 16#80#), (16#57#, 16#77#), (16#60#, 16#78#), (16#61#, 16#78#), (16#62#, 16#08#), (16#63#, 16#50#), (16#7f#, 16#0a#), (16#45#, 16#60#), (16#7f#, 16#00#), (16#4d#, 16#11#), (16#55#, 16#80#), (16#74#, 16#21#), (16#75#, 16#1f#), (16#4a#, 16#78#), (16#4b#, 16#78#), (16#44#, 16#08#), (16#45#, 16#50#), (16#64#, 16#ff#), (16#65#, 16#1f#), (16#7f#, 16#14#), (16#65#, 16#67#), (16#66#, 16#08#), (16#63#, 16#70#), (16#7f#, 16#15#), (16#48#, 16#48#), (16#7f#, 16#07#), (16#41#, 16#0d#), (16#43#, 16#14#), (16#4b#, 16#0e#), (16#45#, 16#0f#), (16#44#, 16#42#), (16#4c#, 16#80#), (16#7f#, 16#10#), (16#5b#, 16#02#), (16#7f#, 16#07#), (16#40#, 16#41#), (16#70#, 16#00#))); This.Timing.Delay_Milliseconds (16#0a#); Write_Magics (((16#32#, 16#44#), (16#7f#, 16#07#), (16#40#, 16#40#), (16#7f#, 16#06#), (16#62#, 16#f0#), (16#63#, 16#00#), (16#7f#, 16#0d#), (16#48#, 16#c0#), (16#6f#, 16#d5#), (16#7f#, 16#00#), (16#5b#, 16#a0#), (16#4e#, 16#a8#), (16#5a#, 16#50#), (16#40#, 16#80#))); This.Timing.Delay_Milliseconds (16#f0#); -- enable LED pulsing??? what LED? Write_Magics (((16#7f#, 16#14#), (16#6f#, 16#1c#), (16#7f#, 16#00#))); end Calibrate; ----------------- -- Read_Motion -- ----------------- function Read_Motion (This : in out PMW3901_Flow_Sensor) return Motion is subtype Buffer is HAL.SPI.SPI_Data_8b (1 .. 12); function Convert is new Ada.Unchecked_Conversion (Buffer, Motion); Buff : Buffer := (others => 0); Status : HAL.SPI.SPI_Status; use all type HAL.SPI.SPI_Status; begin This.CS.Clear; This.Port.Transmit (HAL.SPI.SPI_Data_8b'((1 => Reg_Motion_Burst)), Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI transmit failure"; end if; This.Port.Receive (Buff, Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI receive burst failure"; end if; This.CS.Set; return Convert (Buff); end Read_Motion; ---------- -- Read -- ---------- function Read (This : in out PMW3901_Flow_Sensor; Register : HAL.UInt8) return HAL.UInt8 is use type HAL.UInt8; Register_For_Read : constant HAL.UInt8 := Register and 16#7f#; Data : HAL.SPI.SPI_Data_8b (0 .. 0); Status : HAL.SPI.SPI_Status; use all type HAL.SPI.SPI_Status; begin This.CS.Clear; This.Port.Transmit (HAL.SPI.SPI_Data_8b'(1 => Register_For_Read), Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI transmit failure"; end if; This.Port.Receive (Data, Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI receive failure"; end if; This.CS.Set; return Data (Data'First); end Read; ----------- -- Write -- ----------- procedure Write (This : in out PMW3901_Flow_Sensor; Register : HAL.UInt8; Value : HAL.UInt8) is use type HAL.UInt8; Register_For_Write : constant HAL.UInt8 := Register or 16#80#; Status : HAL.SPI.SPI_Status; use all type HAL.SPI.SPI_Status; begin This.CS.Clear; This.Port.Transmit (HAL.SPI.SPI_Data_8b'(1 => Register_For_Write), Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI transmit failure"; end if; This.Port.Transmit (HAL.SPI.SPI_Data_8b'(1 => Value), Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI transmit failure"; end if; This.CS.Set; end Write; end PMW3901;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2020, AdaCore -- -- Copyright (C) 2020-2021, Simon Wright ([email protected]) -- -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ -- The algorithms used here are derived from Pimoroni's code at -- https://github.com/pimoroni/pmw3901-python. -- Calibration data from PX4: https://github.com/PX4/PX4-Autopilot/ -- blob/master/src/drivers/optical_flow/pmw3901/PMW3901.cpp with Ada.Unchecked_Conversion; package body PMW3901 is -- Some registers Reg_ID : constant := 16#00#; Reg_ID_Inverted : constant := 16#5f#; Reg_Data_Ready : constant := 16#02#; Reg_Motion_Burst : constant := 16#16#; Reg_Power_Up_Reset : constant := 16#3a#; -- Reg_Orientation : constant := 16#5b#; Power_Up_Reset_Key : constant := 16#5a#; function Read (This : in out PMW3901_Flow_Sensor; Register : HAL.UInt8) return HAL.UInt8; procedure Write (This : in out PMW3901_Flow_Sensor; Register : HAL.UInt8; Value : HAL.UInt8); -------------- -- Is_Valid -- -------------- function Is_Valid (M : Motion) return Boolean is use type HAL.UInt8; begin return M.Motion_Occurred and not (M.S_Qual < 19 and M.Shutter_Upper = 16#1f#); end Is_Valid; ---------------- -- Initialize -- ---------------- procedure Initialize (This : in out PMW3901_Flow_Sensor) is begin This.CS.Clear; This.Timing.Delay_Milliseconds (50); This.CS.Set; declare Chip_ID : HAL.UInt8; Revision : HAL.UInt8; Inverted_Chip_ID : HAL.UInt8; use type HAL.UInt8; begin Chip_ID := Read (This, Reg_ID); Revision := Read (This, Reg_ID + 1); Inverted_Chip_ID := Read (This, Reg_ID_Inverted); if Chip_ID /= 16#49# or Revision /= 16#00# or Inverted_Chip_ID /= 16#b6# then -- Can't initialize the wrong sort of chip! raise SPI_Error with "no PMW3901 found"; end if; end; Write (This, Reg_Power_Up_Reset, Power_Up_Reset_Key); This.Timing.Delay_Milliseconds (5); -- Read the registers once declare Buff : HAL.SPI.SPI_Data_8b (0 .. 4); use type HAL.UInt8; begin for J in Buff'Range loop Buff (J) := Read (This, Reg_Data_Ready + HAL.UInt8 (J)); end loop; end; This.Timing.Delay_Milliseconds (1); This.Initialized := True; end Initialize; --------------- -- Calibrate -- --------------- procedure Calibrate (This : in out PMW3901_Flow_Sensor) is type Magic is record Register : HAL.UInt8; Value : HAL.UInt8; end record; type Magics is array (Natural range <>) of Magic; procedure Write_Magics (Data : Magics); procedure Write_Magics (Data : Magics) is begin for J in Data'Range loop Write (This, Data (J).Register, Data (J).Value); end loop; end Write_Magics; use type HAL.UInt8; begin Write_Magics (((16#7f#, 16#00#), (16#55#, 16#01#), (16#50#, 16#07#), (16#7f#, 16#0e#), (16#43#, 16#10#))); declare Check : constant HAL.UInt8 := Read (This, 16#67#); begin if (Check and 2#1000_0000#) /= 0 then Write (This, 16#48#, 16#04#); else Write (This, 16#48#, 16#02#); end if; end; Write_Magics (((16#7f#, 16#00#), (16#51#, 16#7b#), (16#50#, 16#00#), (16#55#, 16#00#), (16#7f#, 16#0e#))); if Read (This, 16#73#) = 0 then declare C1, C2 : HAL.UInt8; begin C1 := Read (This, 16#70#); if C1 <= 28 then C1 := C1 + 14; else C1 := C1 + 11; end if; C1 := HAL.UInt8'Min (16#3f#, C1); C2 := Read (This, 16#71#); C2 := (C2 * 45) / 100; Write_Magics (((16#7f#, 16#00#), (16#61#, 16#ad#), (16#51#, 16#70#), (16#7f#, 16#0E#), (16#70#, C1), (16#71#, C2))); end; end if; Write_Magics (((16#7F#, 16#00#), (16#61#, 16#AD#), (16#7F#, 16#03#), (16#40#, 16#00#), (16#7F#, 16#05#), (16#41#, 16#B3#), (16#43#, 16#F1#), (16#45#, 16#14#), (16#5B#, 16#32#), (16#5F#, 16#34#), (16#7B#, 16#08#), (16#7F#, 16#06#), (16#44#, 16#1B#), (16#40#, 16#BF#), (16#4E#, 16#3F#), (16#7F#, 16#08#), (16#65#, 16#20#), (16#6A#, 16#18#), (16#7F#, 16#09#), (16#4F#, 16#AF#), (16#5F#, 16#40#), (16#48#, 16#80#), (16#49#, 16#80#), (16#57#, 16#77#), (16#60#, 16#78#), (16#61#, 16#78#), (16#62#, 16#08#), (16#63#, 16#50#), (16#7F#, 16#0A#), (16#45#, 16#60#), (16#7F#, 16#00#), (16#4D#, 16#11#), (16#55#, 16#80#), (16#74#, 16#21#), (16#75#, 16#1F#), (16#4A#, 16#78#), (16#4B#, 16#78#), (16#44#, 16#08#), (16#45#, 16#50#), (16#64#, 16#FF#), (16#65#, 16#1F#), (16#7F#, 16#14#), (16#65#, 16#67#), (16#66#, 16#08#), (16#63#, 16#70#), (16#7F#, 16#15#), (16#48#, 16#48#), (16#7F#, 16#07#), (16#41#, 16#0D#), (16#43#, 16#14#), (16#4B#, 16#0E#), (16#45#, 16#0F#), (16#44#, 16#42#), (16#4C#, 16#80#), (16#7F#, 16#10#), (16#5B#, 16#02#), (16#7F#, 16#07#), (16#40#, 16#41#), (16#70#, 16#00#))); This.Timing.Delay_Milliseconds (10); Write_Magics (((16#32#, 16#44#), (16#7F#, 16#07#), (16#40#, 16#40#), (16#7F#, 16#06#), (16#62#, 16#F0#), (16#63#, 16#00#), (16#7F#, 16#0D#), (16#48#, 16#C0#), (16#6F#, 16#D5#), (16#7F#, 16#00#), (16#5B#, 16#A0#), (16#4E#, 16#A8#), (16#5A#, 16#50#), (16#40#, 16#80#))); end Calibrate; ----------------- -- Read_Motion -- ----------------- function Read_Motion (This : in out PMW3901_Flow_Sensor) return Motion is subtype Buffer is HAL.SPI.SPI_Data_8b (1 .. 12); function Convert is new Ada.Unchecked_Conversion (Buffer, Motion); Buff : Buffer := (others => 0); Status : HAL.SPI.SPI_Status; use all type HAL.SPI.SPI_Status; begin This.CS.Clear; This.Port.Transmit (HAL.SPI.SPI_Data_8b'((1 => Reg_Motion_Burst)), Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI transmit failure"; end if; This.Port.Receive (Buff, Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI receive burst failure"; end if; This.CS.Set; return Convert (Buff); end Read_Motion; ---------- -- Read -- ---------- function Read (This : in out PMW3901_Flow_Sensor; Register : HAL.UInt8) return HAL.UInt8 is use type HAL.UInt8; Register_For_Read : constant HAL.UInt8 := Register and 16#7f#; Data : HAL.SPI.SPI_Data_8b (0 .. 0); Status : HAL.SPI.SPI_Status; use all type HAL.SPI.SPI_Status; begin This.CS.Clear; This.Port.Transmit (HAL.SPI.SPI_Data_8b'(1 => Register_For_Read), Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI transmit failure"; end if; This.Port.Receive (Data, Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI receive failure"; end if; This.CS.Set; return Data (Data'First); end Read; ----------- -- Write -- ----------- procedure Write (This : in out PMW3901_Flow_Sensor; Register : HAL.UInt8; Value : HAL.UInt8) is use type HAL.UInt8; Register_For_Write : constant HAL.UInt8 := Register or 16#80#; Status : HAL.SPI.SPI_Status; use all type HAL.SPI.SPI_Status; begin This.CS.Clear; This.Port.Transmit (HAL.SPI.SPI_Data_8b'(1 => Register_For_Write), Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI transmit failure"; end if; This.Port.Transmit (HAL.SPI.SPI_Data_8b'(1 => Value), Status); if Status /= Ok then raise SPI_Error with "PMW3901 SPI transmit failure"; end if; This.CS.Set; end Write; end PMW3901;
Rework PMW3901 calibration parameters.
Rework PMW3901 calibration parameters. Uses timing/calibration parameters from github PX4/PX4-Autopilot\ /blob/master/src/drivers/optical_flow/pmw3901/PMW3901.cpp. * components/src/motion/pmw3901/pmw3901.adb (Initialize): delays to match PX4 code. (Calibrate): likewise, plus calibration data.
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
19688c1ea4d71bc2e9059c4e965b9b2f9fb1ce6d
src/util-beans-objects-readers.ads
src/util-beans-objects-readers.ads
----------------------------------------------------------------------- -- util-beans-objects-readers -- Datasets -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects.Maps; with Util.Beans.Objects.Vectors; with Util.Serialize.IO; with Util.Stacks; package Util.Beans.Objects.Readers is type Reader is limited new Util.Serialize.IO.Reader with private; -- Start a document. overriding procedure Start_Document (Handler : in out Reader); -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. overriding procedure Start_Object (Handler : in out Reader; Name : in String); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. overriding procedure Finish_Object (Handler : in out Reader; Name : in String); overriding procedure Start_Array (Handler : in out Reader; Name : in String); overriding procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural); -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Reader; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- 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 Reader; Message : in String); private type Object_Context is record Map : Util.Beans.Objects.Maps.Map_Bean_Access; List : Util.Beans.Objects.Vectors.Vector_Bean_Access; end record; type Object_Context_Access is access all Object_Context; package Object_Stack is new Util.Stacks (Element_Type => Object_Context, Element_Type_Access => Object_Context_Access); type Reader is limited new Util.Serialize.IO.Reader with record Context : Object_Stack.Stack; end record; end Util.Beans.Objects.Readers;
----------------------------------------------------------------------- -- util-beans-objects-readers -- Datasets -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects.Maps; with Util.Beans.Objects.Vectors; with Util.Serialize.IO; with Util.Stacks; with Util.Log; package Util.Beans.Objects.Readers is type Reader is limited new Util.Serialize.IO.Reader with private; -- Start a document. overriding procedure Start_Document (Handler : in out Reader); -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. overriding procedure Start_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. overriding procedure Finish_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class); overriding procedure Start_Array (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class); overriding procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class); -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Reader; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False); private type Object_Context is record Map : Util.Beans.Objects.Maps.Map_Bean_Access; List : Util.Beans.Objects.Vectors.Vector_Bean_Access; end record; type Object_Context_Access is access all Object_Context; package Object_Stack is new Util.Stacks (Element_Type => Object_Context, Element_Type_Access => Object_Context_Access); type Reader is limited new Util.Serialize.IO.Reader with record Context : Object_Stack.Stack; end record; end Util.Beans.Objects.Readers;
Add a Logger parameter to the Reader operations Remove the Error procedure which is no longer necessary
Add a Logger parameter to the Reader operations Remove the Error procedure which is no longer necessary
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a782337801939bc14f6fe15597e9633a6ceaa7a8
src/gen-commands-templates.adb
src/gen-commands-templates.adb
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Streams.Stream_IO; with GNAT.Command_Line; with Gen.Artifacts; with EL.Contexts.Default; with EL.Expressions; with EL.Variables.Default; with Util.Log.Loggers; with Util.Files; with Util.Streams.Files; with Util.Streams.Texts; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; package body Gen.Commands.Templates is use Ada.Strings.Unbounded; use GNAT.Command_Line; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Templates"); -- Apply the patch instruction procedure Patch_File (Generator : in out Gen.Generator.Handler; Info : in Patch); function Match_Line (Line : in String; Pattern : in String) return Boolean; -- ------------------------------ -- Check if the line matches the pseudo pattern. -- ------------------------------ function Match_Line (Line : in String; Pattern : in String) return Boolean is L_Pos : Natural := Line'First; P_Pos : Natural := Pattern'First; begin while P_Pos <= Pattern'Last loop if L_Pos > Line'Last then return False; end if; if Line (L_Pos) = Pattern (P_Pos) then if Pattern (P_Pos) /= ' ' then P_Pos := P_Pos + 1; end if; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = ' ' and Line (L_Pos) = Pattern (P_Pos + 1) then P_Pos := P_Pos + 2; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = ' ' and Pattern (P_Pos + 1) = '*' then P_Pos := P_Pos + 1; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = '*' and Line (L_Pos) = Pattern (P_Pos + 1) then P_Pos := P_Pos + 2; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = '*' and Line (L_Pos) /= ' ' then L_Pos := L_Pos + 1; else return False; end if; end loop; return True; end Match_Line; -- ------------------------------ -- Apply the patch instruction -- ------------------------------ procedure Patch_File (Generator : in out Gen.Generator.Handler; Info : in Patch) is procedure Save_Output (H : in out Gen.Generator.Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; procedure Save_Output (H : in out Gen.Generator.Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String) is type State is (MATCH_AFTER, MATCH_BEFORE, MATCH_DONE); Output_Dir : constant String := H.Get_Result_Directory; Path : constant String := Util.Files.Compose (Output_Dir, File); Tmp_File : constant String := Path & ".tmp"; Line_Number : Natural := 0; After_Pos : Natural := 1; Current_State : State := MATCH_AFTER; Tmp_Output : aliased Util.Streams.Files.File_Stream; Output : Util.Streams.Texts.Print_Stream; procedure Process (Line : in String); procedure Process (Line : in String) is begin Line_Number := Line_Number + 1; case Current_State is when MATCH_AFTER => if Match_Line (Line, Info.After.Element (After_Pos)) then Log.Info ("Match after at line {0}", Natural'Image (Line_Number)); After_Pos := After_Pos + 1; if After_Pos >= Natural (Info.After.Length) then Current_State := MATCH_BEFORE; end if; end if; when MATCH_BEFORE => if Match_Line (Line, To_String (Info.Before)) then Log.Info ("Match before at line {0}", Natural'Image (Line_Number)); Log.Info ("Add content {0}", Content); Output.Write (Content); Current_State := MATCH_DONE; end if; when MATCH_DONE => null; end case; Output.Write (Line); Output.Write (ASCII.LF); end Process; begin Tmp_Output.Create (Name => Tmp_File, Mode => Ada.Streams.Stream_IO.Out_File); Output.Initialize (Tmp_Output'Unchecked_Access); Util.Files.Read_File (Path, Process'Access); Output.Close; if Current_State /= MATCH_DONE then H.Error ("Patch {0} failed", Path); Ada.Directories.Delete_File (Tmp_File); else Ada.Directories.Delete_File (Path); Ada.Directories.Rename (Old_Name => Tmp_File, New_Name => Path); end if; exception when Ada.IO_Exceptions.Name_Error => H.Error ("Cannot patch file {0}", Path); end Save_Output; begin Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, To_String (Info.Template), Save_Output'Access); end Patch_File; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is function Get_Output_Dir return String; function Get_Output_Dir return String is Dir : constant String := Generator.Get_Result_Directory; begin if Length (Cmd.Base_Dir) = 0 then return Dir; else return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir)); end if; end Get_Output_Dir; Out_Dir : constant String := Get_Output_Dir; Iter : Param_Vectors.Cursor := Cmd.Params.First; begin Generator.Read_Project ("dynamo.xml", False); while Param_Vectors.Has_Element (Iter) loop declare P : constant Param := Param_Vectors.Element (Iter); Value : constant String := Get_Argument; begin if not P.Is_Optional and Value'Length = 0 then Generator.Error ("Missing argument for {0}", To_String (P.Argument)); return; end if; Generator.Set_Global (To_String (P.Name), Value); end; Param_Vectors.Next (Iter); end loop; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Out_Dir); declare Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First; begin while Util.Strings.Sets.Has_Element (Iter) loop Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, Util.Strings.Sets.Element (Iter), Gen.Generator.Save_Content'Access); Util.Strings.Sets.Next (Iter); end loop; end; -- Apply the patch instructions defined for the command. declare Iter : Patch_Vectors.Cursor := Cmd.Patches.First; begin while Patch_Vectors.Has_Element (Iter) loop Patch_File (Generator, Patch_Vectors.Element (Iter)); Patch_Vectors.Next (Iter); end loop; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Generator); use Ada.Text_IO; begin Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title)); Put_Line ("Usage: " & To_String (Cmd.Usage)); New_Line; Put_Line (To_String (Cmd.Help_Msg)); end Help; type Command_Fields is (FIELD_NAME, FIELD_HELP, FIELD_USAGE, FIELD_TITLE, FIELD_BASEDIR, FIELD_PARAM, FIELD_PARAM_NAME, FIELD_PARAM_OPTIONAL, FIELD_PARAM_ARG, FIELD_TEMPLATE, FIELD_PATCH, FIELD_AFTER, FIELD_BEFORE, FIELD_INSERT_TEMPLATE, FIELD_COMMAND); type Command_Loader is record Command : Command_Access := null; P : Param; Info : Patch; end record; type Command_Loader_Access is access all Command_Loader; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object); function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String; -- ------------------------------ -- Convert the object value into a string and trim any space/tab/newlines. -- ------------------------------ function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is Result : constant String := Util.Beans.Objects.To_String (Value); First_Pos : Natural := Result'First; Last_Pos : Natural := Result'Last; C : Character; begin while First_Pos <= Last_Pos loop C := Result (First_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; First_Pos := First_Pos + 1; end loop; while Last_Pos >= First_Pos loop C := Result (Last_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; Last_Pos := Last_Pos - 1; end loop; return To_Unbounded_String (Result (First_Pos .. Last_Pos)); end To_String; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin if Field = FIELD_COMMAND then if Closure.Command /= null then Log.Info ("Adding command {0}", Closure.Command.Name); Add_Command (Name => To_String (Closure.Command.Name), Cmd => Closure.Command.all'Access); Closure.Command := null; end if; else if Closure.Command = null then Closure.Command := new Gen.Commands.Templates.Command; end if; case Field is when FIELD_NAME => Closure.Command.Name := To_String (Value); when FIELD_TITLE => Closure.Command.Title := To_String (Value); when FIELD_USAGE => Closure.Command.Usage := To_String (Value); when FIELD_HELP => Closure.Command.Help_Msg := To_String (Value); when FIELD_TEMPLATE => Closure.Command.Templates.Include (To_String (Value)); when FIELD_PARAM_NAME => Closure.P.Name := To_Unbounded_String (Value); when FIELD_PARAM_OPTIONAL => Closure.P.Is_Optional := To_Boolean (Value); when FIELD_PARAM_ARG => Closure.P.Argument := To_Unbounded_String (Value); when FIELD_PARAM => Closure.P.Value := To_Unbounded_String (Value); Closure.Command.Params.Append (Closure.P); Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Is_Optional := False; when FIELD_BASEDIR => Closure.Command.Base_Dir := To_Unbounded_String (Value); when FIELD_COMMAND => null; when FIELD_INSERT_TEMPLATE => Closure.Info.Template := To_Unbounded_String (Value); when FIELD_AFTER => Closure.Info.After.Append (To_String (Value)); when FIELD_BEFORE => Closure.Info.Before := To_Unbounded_String (Value); when FIELD_PATCH => Closure.Command.Patches.Append (Closure.Info); Closure.Info.After.Clear; Closure.Info.Before := To_Unbounded_String (""); end case; end if; end Set_Member; package Command_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader, Element_Type_Access => Command_Loader_Access, Fields => Command_Fields, Set_Member => Set_Member); Cmd_Mapper : aliased Command_Mapper.Mapper; -- ------------------------------ -- Read the template commands defined in dynamo configuration directory. -- ------------------------------ procedure Read_Commands (Generator : in out Gen.Generator.Handler) is procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Read the XML command file. -- ------------------------------ procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean) is pragma Unreferenced (Name); Loader : aliased Command_Loader; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading command file '{0}'", File_Path); Done := False; -- Create the mapping to load the XML command file. Reader.Add_Mapping ("commands", Cmd_Mapper'Access); -- Set the context for Set_Member. Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access); -- Read the XML command file. Reader.Parse (File_Path); exception when Ada.IO_Exceptions.Name_Error => Generator.Error ("Command file {0} does not exist", File_Path); end Read_Command; Config_Dir : constant String := Generator.Get_Config_Directory; Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir"); Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir); begin Log.Debug ("Checking commands in {0}", Path); if Ada.Directories.Exists (Path) then Util.Files.Iterate_Files_Path (Path => Path, Pattern => "*.xml", Process => Read_Command'Access); end if; end Read_Commands; begin -- Setup the mapper to load XML commands. Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME); Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE); Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE); Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP); Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR); Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM); Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME); Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL); Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG); Cmd_Mapper.Add_Mapping ("command/patch/template", FIELD_INSERT_TEMPLATE); Cmd_Mapper.Add_Mapping ("command/patch/after", FIELD_AFTER); Cmd_Mapper.Add_Mapping ("command/patch/before", FIELD_BEFORE); Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE); Cmd_Mapper.Add_Mapping ("command/patch", FIELD_PATCH); Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND); end Gen.Commands.Templates;
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Streams.Stream_IO; with GNAT.Command_Line; with Gen.Artifacts; with EL.Contexts.Default; with EL.Expressions; with EL.Variables.Default; with Util.Log.Loggers; with Util.Files; with Util.Streams.Files; with Util.Streams.Texts; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; package body Gen.Commands.Templates is use Ada.Strings.Unbounded; use GNAT.Command_Line; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Templates"); -- Apply the patch instruction procedure Patch_File (Generator : in out Gen.Generator.Handler; Info : in Patch); function Match_Line (Line : in String; Pattern : in String) return Boolean; -- ------------------------------ -- Check if the line matches the pseudo pattern. -- ------------------------------ function Match_Line (Line : in String; Pattern : in String) return Boolean is L_Pos : Natural := Line'First; P_Pos : Natural := Pattern'First; begin while P_Pos <= Pattern'Last loop if L_Pos > Line'Last then return False; end if; if Line (L_Pos) = Pattern (P_Pos) then if Pattern (P_Pos) /= ' ' then P_Pos := P_Pos + 1; end if; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = ' ' and then Line (L_Pos) = Pattern (P_Pos + 1) then P_Pos := P_Pos + 2; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = ' ' and then Pattern (P_Pos + 1) = '*' then P_Pos := P_Pos + 1; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = '*' and then Line (L_Pos) = Pattern (P_Pos + 1) then P_Pos := P_Pos + 2; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = '*' and Line (L_Pos) /= ' ' then L_Pos := L_Pos + 1; else return False; end if; end loop; return True; end Match_Line; -- ------------------------------ -- Apply the patch instruction -- ------------------------------ procedure Patch_File (Generator : in out Gen.Generator.Handler; Info : in Patch) is procedure Save_Output (H : in out Gen.Generator.Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; procedure Save_Output (H : in out Gen.Generator.Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String) is type State is (MATCH_AFTER, MATCH_BEFORE, MATCH_DONE); Output_Dir : constant String := H.Get_Result_Directory; Path : constant String := Util.Files.Compose (Output_Dir, File); Tmp_File : constant String := Path & ".tmp"; Line_Number : Natural := 0; After_Pos : Natural := 1; Current_State : State := MATCH_AFTER; Tmp_Output : aliased Util.Streams.Files.File_Stream; Output : Util.Streams.Texts.Print_Stream; procedure Process (Line : in String); procedure Process (Line : in String) is begin Line_Number := Line_Number + 1; case Current_State is when MATCH_AFTER => if Match_Line (Line, Info.After.Element (After_Pos)) then Log.Info ("Match after at line {0}", Natural'Image (Line_Number)); After_Pos := After_Pos + 1; if After_Pos > Natural (Info.After.Length) then Current_State := MATCH_BEFORE; end if; end if; when MATCH_BEFORE => if Match_Line (Line, To_String (Info.Before)) then Log.Info ("Match before at line {0}", Natural'Image (Line_Number)); Log.Info ("Add content {0}", Content); Output.Write (Content); Current_State := MATCH_DONE; end if; when MATCH_DONE => null; end case; Output.Write (Line); Output.Write (ASCII.LF); end Process; begin Tmp_Output.Create (Name => Tmp_File, Mode => Ada.Streams.Stream_IO.Out_File); Output.Initialize (Tmp_Output'Unchecked_Access); Util.Files.Read_File (Path, Process'Access); Output.Close; if Current_State /= MATCH_DONE then H.Error ("Patch {0} failed", Path); Ada.Directories.Delete_File (Tmp_File); else Ada.Directories.Delete_File (Path); Ada.Directories.Rename (Old_Name => Tmp_File, New_Name => Path); end if; exception when Ada.IO_Exceptions.Name_Error => H.Error ("Cannot patch file {0}", Path); end Save_Output; begin Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, To_String (Info.Template), Save_Output'Access); end Patch_File; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is function Get_Output_Dir return String; function Get_Output_Dir return String is Dir : constant String := Generator.Get_Result_Directory; begin if Length (Cmd.Base_Dir) = 0 then return Dir; else return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir)); end if; end Get_Output_Dir; Out_Dir : constant String := Get_Output_Dir; Iter : Param_Vectors.Cursor := Cmd.Params.First; begin Generator.Read_Project ("dynamo.xml", False); while Param_Vectors.Has_Element (Iter) loop declare P : constant Param := Param_Vectors.Element (Iter); Value : constant String := Get_Argument; begin if not P.Is_Optional and Value'Length = 0 then Generator.Error ("Missing argument for {0}", To_String (P.Argument)); return; end if; Generator.Set_Global (To_String (P.Name), Value); end; Param_Vectors.Next (Iter); end loop; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Out_Dir); declare Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First; begin while Util.Strings.Sets.Has_Element (Iter) loop Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, Util.Strings.Sets.Element (Iter), Gen.Generator.Save_Content'Access); Util.Strings.Sets.Next (Iter); end loop; end; -- Apply the patch instructions defined for the command. declare Iter : Patch_Vectors.Cursor := Cmd.Patches.First; begin while Patch_Vectors.Has_Element (Iter) loop Patch_File (Generator, Patch_Vectors.Element (Iter)); Patch_Vectors.Next (Iter); end loop; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Generator); use Ada.Text_IO; begin Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title)); Put_Line ("Usage: " & To_String (Cmd.Usage)); New_Line; Put_Line (To_String (Cmd.Help_Msg)); end Help; type Command_Fields is (FIELD_NAME, FIELD_HELP, FIELD_USAGE, FIELD_TITLE, FIELD_BASEDIR, FIELD_PARAM, FIELD_PARAM_NAME, FIELD_PARAM_OPTIONAL, FIELD_PARAM_ARG, FIELD_TEMPLATE, FIELD_PATCH, FIELD_AFTER, FIELD_BEFORE, FIELD_INSERT_TEMPLATE, FIELD_COMMAND); type Command_Loader is record Command : Command_Access := null; P : Param; Info : Patch; end record; type Command_Loader_Access is access all Command_Loader; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object); function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String; -- ------------------------------ -- Convert the object value into a string and trim any space/tab/newlines. -- ------------------------------ function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is Result : constant String := Util.Beans.Objects.To_String (Value); First_Pos : Natural := Result'First; Last_Pos : Natural := Result'Last; C : Character; begin while First_Pos <= Last_Pos loop C := Result (First_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; First_Pos := First_Pos + 1; end loop; while Last_Pos >= First_Pos loop C := Result (Last_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; Last_Pos := Last_Pos - 1; end loop; return To_Unbounded_String (Result (First_Pos .. Last_Pos)); end To_String; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin if Field = FIELD_COMMAND then if Closure.Command /= null then Log.Info ("Adding command {0}", Closure.Command.Name); Add_Command (Name => To_String (Closure.Command.Name), Cmd => Closure.Command.all'Access); Closure.Command := null; end if; else if Closure.Command = null then Closure.Command := new Gen.Commands.Templates.Command; end if; case Field is when FIELD_NAME => Closure.Command.Name := To_String (Value); when FIELD_TITLE => Closure.Command.Title := To_String (Value); when FIELD_USAGE => Closure.Command.Usage := To_String (Value); when FIELD_HELP => Closure.Command.Help_Msg := To_String (Value); when FIELD_TEMPLATE => Closure.Command.Templates.Include (To_String (Value)); when FIELD_PARAM_NAME => Closure.P.Name := To_Unbounded_String (Value); when FIELD_PARAM_OPTIONAL => Closure.P.Is_Optional := To_Boolean (Value); when FIELD_PARAM_ARG => Closure.P.Argument := To_Unbounded_String (Value); when FIELD_PARAM => Closure.P.Value := To_Unbounded_String (Value); Closure.Command.Params.Append (Closure.P); Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Is_Optional := False; when FIELD_BASEDIR => Closure.Command.Base_Dir := To_Unbounded_String (Value); when FIELD_COMMAND => null; when FIELD_INSERT_TEMPLATE => Closure.Info.Template := To_Unbounded_String (Value); when FIELD_AFTER => Closure.Info.After.Append (To_String (Value)); when FIELD_BEFORE => Closure.Info.Before := To_Unbounded_String (Value); when FIELD_PATCH => Closure.Command.Patches.Append (Closure.Info); Closure.Info.After.Clear; Closure.Info.Before := To_Unbounded_String (""); end case; end if; end Set_Member; package Command_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader, Element_Type_Access => Command_Loader_Access, Fields => Command_Fields, Set_Member => Set_Member); Cmd_Mapper : aliased Command_Mapper.Mapper; -- ------------------------------ -- Read the template commands defined in dynamo configuration directory. -- ------------------------------ procedure Read_Commands (Generator : in out Gen.Generator.Handler) is procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Read the XML command file. -- ------------------------------ procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean) is pragma Unreferenced (Name); Loader : aliased Command_Loader; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading command file '{0}'", File_Path); Done := False; -- Create the mapping to load the XML command file. Reader.Add_Mapping ("commands", Cmd_Mapper'Access); -- Set the context for Set_Member. Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access); -- Read the XML command file. Reader.Parse (File_Path); exception when Ada.IO_Exceptions.Name_Error => Generator.Error ("Command file {0} does not exist", File_Path); end Read_Command; Config_Dir : constant String := Generator.Get_Config_Directory; Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir"); Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir); begin Log.Debug ("Checking commands in {0}", Path); if Ada.Directories.Exists (Path) then Util.Files.Iterate_Files_Path (Path => Path, Pattern => "*.xml", Process => Read_Command'Access); end if; end Read_Commands; begin -- Setup the mapper to load XML commands. Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME); Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE); Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE); Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP); Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR); Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM); Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME); Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL); Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG); Cmd_Mapper.Add_Mapping ("command/patch/template", FIELD_INSERT_TEMPLATE); Cmd_Mapper.Add_Mapping ("command/patch/after", FIELD_AFTER); Cmd_Mapper.Add_Mapping ("command/patch/before", FIELD_BEFORE); Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE); Cmd_Mapper.Add_Mapping ("command/patch", FIELD_PATCH); Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND); end Gen.Commands.Templates;
Fix matching rules when executing a patch command
Fix matching rules when executing a patch command
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
2d35ad2531eae51771a675b6973d5dfb5c835d68
matp/src/mat-targets.ads
matp/src/mat-targets.ads
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with Ada.Finalization; with GNAT.Sockets; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Events.Targets; with MAT.Events.Probes; with MAT.Readers; with MAT.Readers.Streams; with MAT.Readers.Streams.Sockets; with MAT.Consoles; with MAT.Expressions; package MAT.Targets is -- Exception raised if some option is invalid. Usage_Error : exception; -- The options that can be configured through the command line. type Options_Type is record -- Enable and enter in the interactive TTY console mode. Interactive : Boolean := True; -- Try to load the symbol file automatically when a new process is received. Load_Symbols : Boolean := True; -- Enable the graphical mode (when available). Graphical : Boolean := False; -- Print the events as they are received. Print_Events : Boolean := False; -- The library search path. Search_Path : Ada.Strings.Unbounded.Unbounded_String; -- Define the server listening address. Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; type Target_Process_Type is new Ada.Finalization.Limited_Controlled and MAT.Expressions.Resolver_Type with record Pid : MAT.Types.Target_Process_Ref; Endian : MAT.Readers.Endian_Type := MAT.Readers.LITTLE_ENDIAN; Path : Ada.Strings.Unbounded.Unbounded_String; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Events : MAT.Events.Targets.Target_Events_Access; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; -- Release the target process instance. overriding procedure Finalize (Target : in out Target_Process_Type); -- Find the region that matches the given name. overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info; -- Find the symbol in the symbol table and return the start and end address. overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Events.Probes.Reader_List_Type with private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. overriding procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)); -- Add a search path for the library and symbol loader. procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out Target_Type); -- 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); -- Start the server to listen to MAT event socket streams. procedure Start (Target : in out Target_Type); -- Stop the server thread. procedure Stop (Target : in out Target_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Events.Probes.Reader_List_Type with record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; Options : Options_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; end record; -- Release the storage used by the target object. overriding procedure Finalize (Target : in out Target_Type); end MAT.Targets;
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with Ada.Finalization; with GNAT.Sockets; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Events.Targets; with MAT.Events.Probes; with MAT.Readers; with MAT.Readers.Streams; with MAT.Readers.Streams.Sockets; with MAT.Consoles; with MAT.Expressions; package MAT.Targets is -- Exception raised if some option is invalid. Usage_Error : exception; -- The options that can be configured through the command line. type Options_Type is record -- Enable and enter in the interactive TTY console mode. Interactive : Boolean := True; -- Try to load the symbol file automatically when a new process is received. Load_Symbols : Boolean := True; -- Enable the graphical mode (when available). Graphical : Boolean := False; -- Print the events as they are received. Print_Events : Boolean := False; -- The library search path. Search_Path : Ada.Strings.Unbounded.Unbounded_String; -- Define the server listening address. Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; type Target_Process_Type is new Ada.Finalization.Limited_Controlled and MAT.Expressions.Resolver_Type with record Pid : MAT.Types.Target_Process_Ref; Endian : MAT.Readers.Endian_Type := MAT.Readers.LITTLE_ENDIAN; Path : Ada.Strings.Unbounded.Unbounded_String; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Events : MAT.Events.Targets.Target_Events_Access; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; -- Release the target process instance. overriding procedure Finalize (Target : in out Target_Process_Type); -- Find the region that matches the given name. overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info; -- Find the symbol in the symbol table and return the start and end address. overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info; -- Get the start time for the tick reference. overriding function Get_Start_Time (Resolver : in Target_Process_Type) return MAT.Types.Target_Tick_Ref; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Events.Probes.Reader_List_Type with private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. overriding procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)); -- Add a search path for the library and symbol loader. procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out Target_Type); -- 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); -- Start the server to listen to MAT event socket streams. procedure Start (Target : in out Target_Type); -- Stop the server thread. procedure Stop (Target : in out Target_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Events.Probes.Reader_List_Type with record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; Options : Options_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; end record; -- Release the storage used by the target object. overriding procedure Finalize (Target : in out Target_Type); end MAT.Targets;
Declare the Get_Start_Time abstract function for the Target_Process_Type
Declare the Get_Start_Time abstract function for the Target_Process_Type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
81546e3ed518c116bf77e4dca3a649cdf7e876cd
regtests/asf-applications-views-tests.adb
regtests/asf-applications-views-tests.adb
----------------------------------------------------------------------- -- Render Tests - Unit tests for ASF.Applications.Views -- Copyright (C) 2009, 2010, 2011, 2012, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with ASF.Applications.Main; with ASF.Applications.Tests; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Servlets.Faces; with ASF.Converters.Dates; with ASF.Server; with Ada.Directories; with Ada.Unchecked_Deallocation; with Util.Files; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Measures; package body ASF.Applications.Views.Tests is use Ada.Strings.Unbounded; overriding procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- Set up performed before each test case -- ------------------------------ -- Test loading of facelet file -- ------------------------------ procedure Test_Load_Facelet (T : in out Test) is use ASF.Contexts.Faces; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Dates.Date_Converter'Class, Name => ASF.Converters.Dates.Date_Converter_Access); App : aliased Applications.Main.Application; View_Name : constant String := To_String (T.File); Result_File : constant String := To_String (T.Result); Conf : Applications.Config; App_Factory : Applications.Main.Application_Factory; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); Faces : aliased ASF.Servlets.Faces.Faces_Servlet; List : Util.Beans.Basic.Readonly_Bean_Access; List_Bean : Util.Beans.Objects.Object; Form : Util.Beans.Basic.Readonly_Bean_Access; Form_Bean : Util.Beans.Objects.Object; C : ASF.Converters.Dates.Date_Converter_Access; Container : ASF.Server.Container; begin List := Applications.Tests.Create_Form_List; List_Bean := Util.Beans.Objects.To_Object (List); Form := Applications.Tests.Create_Form_Bean; Form_Bean := Util.Beans.Objects.To_Object (Form); Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); App.Initialize (Conf, App_Factory); App.Register_Application ("/"); App.Add_Servlet ("faces", Faces'Unchecked_Access); App.Add_Mapping ("*.xhtml", "faces"); C := ASF.Converters.Dates.Create_Date_Converter (Date => ASF.Converters.Dates.DEFAULT, Time => ASF.Converters.Dates.DEFAULT, Format => ASF.Converters.Dates.TIME, Locale => "en", Pattern => ""); App.Add_Converter ("date-default-converter", C.all'Access); App.Set_Global ("function", "Test_Load_Facelet"); App.Set_Global ("date", "2011-12-03 03:04:05.23"); Container.Register_Application ("/asfunit", App'Unchecked_Access); for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Req : ASF.Requests.Mockup.Request; Reply : aliased ASF.Responses.Mockup.Response; Content : Unbounded_String; begin Req.Set_Method ("GET"); Req.Set_Request_URI ("/asfunit/" & View_Name); Req.Set_Parameter ("file-name", To_String (T.Name)); Req.Set_Header ("file", To_String (T.Name)); Req.Set_Attribute ("list", List_Bean); Req.Set_Attribute ("form", Form_Bean); Container.Service (Req, Reply); Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view " & View_Name); Reply.Read_Content (Content); Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Restore and render view"); end; end loop; Free (C); end Test_Load_Facelet; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : Test) return Util.Tests.Message_String is begin return Util.Tests.Format ("Test " & To_String (T.Name)); end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Load_Facelet; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.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 : constant 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); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" then Tst := new Test; Tst.Name := To_Unbounded_String (Dir & "/" & Simple); Tst.File := To_Unbounded_String ("views/" & Simple); Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple); Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple); Suite.Add_Test (Tst.all'Access); 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, 2011, 2012, 2014, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with ASF.Applications.Main; with ASF.Applications.Tests; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Servlets.Faces; with ASF.Converters.Dates; with ASF.Server; with Ada.Directories; with Ada.Unchecked_Deallocation; with Util.Files; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Measures; package body ASF.Applications.Views.Tests is use Ada.Strings.Unbounded; overriding procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- Set up performed before each test case -- ------------------------------ -- Test loading of facelet file -- ------------------------------ procedure Test_Load_Facelet (T : in out Test) is use ASF.Contexts.Faces; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Dates.Date_Converter'Class, Name => ASF.Converters.Dates.Date_Converter_Access); App : aliased Applications.Main.Application; View_Name : constant String := To_String (T.File); Result_File : constant String := To_String (T.Result); Conf : Applications.Config; App_Factory : Applications.Main.Application_Factory; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); Faces : aliased ASF.Servlets.Faces.Faces_Servlet; List : Util.Beans.Basic.Readonly_Bean_Access; List_Bean : Util.Beans.Objects.Object; Form : Util.Beans.Basic.Readonly_Bean_Access; Form_Bean : Util.Beans.Objects.Object; C : ASF.Converters.Dates.Date_Converter_Access; Container : ASF.Server.Container; begin List := Applications.Tests.Create_Form_List; List_Bean := Util.Beans.Objects.To_Object (List); Form := Applications.Tests.Create_Form_Bean; Form_Bean := Util.Beans.Objects.To_Object (Form); Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); App.Initialize (Conf, App_Factory); App.Register_Application ("/"); App.Add_Servlet ("faces", Faces'Unchecked_Access); App.Add_Mapping ("*.xhtml", "faces"); C := ASF.Converters.Dates.Create_Date_Converter (Date => ASF.Converters.Dates.DEFAULT, Time => ASF.Converters.Dates.DEFAULT, Format => ASF.Converters.Dates.TIME, Locale => "en", Pattern => ""); App.Add_Converter ("date-default-converter", C.all'Access); App.Set_Global ("function", "Test_Load_Facelet"); App.Set_Global ("date", "2011-12-03 03:04:05.23"); Container.Register_Application ("/asfunit", App'Unchecked_Access); Container.Start; for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Req : ASF.Requests.Mockup.Request; Reply : aliased ASF.Responses.Mockup.Response; Content : Unbounded_String; begin Req.Set_Method ("GET"); Req.Set_Request_URI ("/asfunit/" & View_Name); Req.Set_Parameter ("file-name", To_String (T.Name)); Req.Set_Header ("file", To_String (T.Name)); Req.Set_Attribute ("list", List_Bean); Req.Set_Attribute ("form", Form_Bean); Container.Service (Req, Reply); Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view " & View_Name); Reply.Read_Content (Content); Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Restore and render view"); end; end loop; Free (C); end Test_Load_Facelet; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : Test) return Util.Tests.Message_String is begin return Util.Tests.Format ("Test " & To_String (T.Name)); end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Load_Facelet; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.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 : constant 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); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" then Tst := new Test; Tst.Name := To_Unbounded_String (Dir & "/" & Simple); Tst.File := To_Unbounded_String ("views/" & Simple); Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple); Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Tests; end ASF.Applications.Views.Tests;
Call the Start procedure on the servlet registry
Call the Start procedure on the servlet registry
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
4d75440dc0b5e3de6009b04d761f37b440b31034
regtests/asf-applications-views-tests.adb
regtests/asf-applications-views-tests.adb
----------------------------------------------------------------------- -- Render Tests - Unit tests for ASF.Applications.Views -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with Ada.Directories; with Util.Test_Caller; with Util.Files; with Util.Measures; package body ASF.Applications.Views.Tests is use Ada.Strings.Unbounded; overriding procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- Set up performed before each test case -- Test loading of facelet file procedure Test_Load_Facelet (T : in out Test) is use ASF; use ASF.Contexts.Faces; App : Applications.Main.Application; -- H : Applications.Views.View_Handler; View_Name : constant String := To_String (T.File); Result_File : constant String := To_String (T.Result); Conf : Applications.Config; App_Factory : Applications.Main.Application_Factory; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); begin Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); App.Initialize (Conf, App_Factory); App.Set_Global ("function", "Test_Load_Facelet"); for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Req : ASF.Requests.Mockup.Request; Rep : ASF.Responses.Mockup.Response; Content : Unbounded_String; begin Req.Set_Method ("GET"); Req.Set_Path_Info (View_Name); Req.Set_Parameter ("file-name", To_String (T.Name)); Req.Set_Header ("file", To_String (T.Name)); App.Dispatch (Page => View_Name, Request => Req, Response => Rep); Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view " & View_Name); Rep.Read_Content (Content); Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Restore and render view"); end; end loop; end Test_Load_Facelet; -- Test case name overriding function Name (T : Test) return Util.Tests.Message_String is begin return Util.Tests.Format ("Test " & To_String (T.Name)); end Name; -- Perform the test. overriding procedure Run_Test (T : in out Test) is begin T.Test_Load_Facelet; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.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 : constant 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); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" then Tst := new Test; Tst.Name := To_Unbounded_String (Dir & "/" & Simple); Tst.File := To_Unbounded_String ("views/" & Simple); Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple); Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple); Suite.Add_Test (Tst); 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, 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 ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with Ada.Directories; with Util.Test_Caller; with Util.Files; with Util.Measures; package body ASF.Applications.Views.Tests is use Ada.Strings.Unbounded; overriding procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- Set up performed before each test case -- Test loading of facelet file procedure Test_Load_Facelet (T : in out Test) is use ASF; use ASF.Contexts.Faces; App : Applications.Main.Application; -- H : Applications.Views.View_Handler; View_Name : constant String := To_String (T.File); Result_File : constant String := To_String (T.Result); Conf : Applications.Config; App_Factory : Applications.Main.Application_Factory; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); begin Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); App.Initialize (Conf, App_Factory); App.Set_Global ("function", "Test_Load_Facelet"); for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Req : ASF.Requests.Mockup.Request; Rep : ASF.Responses.Mockup.Response; Content : Unbounded_String; begin Req.Set_Method ("GET"); Req.Set_Path_Info (View_Name); Req.Set_Parameter ("file-name", To_String (T.Name)); Req.Set_Header ("file", To_String (T.Name)); App.Dispatch (Page => View_Name, Request => Req, Response => Rep); Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view " & View_Name); Rep.Read_Content (Content); Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Restore and render view"); end; end loop; end Test_Load_Facelet; -- Test case name overriding function Name (T : Test) return Util.Tests.Message_String is begin return Util.Tests.Format ("Test " & To_String (T.Name)); end Name; -- Perform the test. overriding procedure Run_Test (T : in out Test) is begin T.Test_Load_Facelet; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.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 : constant 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); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" then Tst := new Test; Tst.Name := To_Unbounded_String (Dir & "/" & Simple); Tst.File := To_Unbounded_String ("views/" & Simple); Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple); Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Tests; end ASF.Applications.Views.Tests;
Fix compilation when Ahven is used as a test framework
Fix compilation when Ahven is used as a test framework
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
77324d884ea68519a192af84cc50ed9179b6074f
regtests/util-strings-tests.ads
regtests/util-strings-tests.ads
----------------------------------------------------------------------- -- strings.tests -- Unit tests for Strings -- 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 Util.Tests; package Util.Strings.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Escape_Javascript (T : in out Test); procedure Test_Escape_Xml (T : in out Test); procedure Test_Unescape_Xml (T : in out Test); procedure Test_Capitalize (T : in out Test); procedure Test_To_Upper_Case (T : in out Test); procedure Test_To_Lower_Case (T : in out Test); procedure Test_To_Hex (T : in out Test); procedure Test_Measure_Copy (T : in out Test); procedure Test_Index (T : in out Test); procedure Test_Rindex (T : in out Test); -- Do some benchmark on String -> X hash mapped. procedure Test_Measure_Hash (T : in out Test); -- Test String_Ref creation procedure Test_String_Ref (T : in out Test); -- Test perfect hash (samples/gperfhash) procedure Test_Perfect_Hash (T : in out Test); -- Test the token iteration. procedure Test_Iterate_Token (T : in out Test); end Util.Strings.Tests;
----------------------------------------------------------------------- -- strings.tests -- Unit tests for Strings -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Strings.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Escape_Javascript (T : in out Test); procedure Test_Escape_Xml (T : in out Test); procedure Test_Unescape_Xml (T : in out Test); procedure Test_Capitalize (T : in out Test); procedure Test_To_Upper_Case (T : in out Test); procedure Test_To_Lower_Case (T : in out Test); procedure Test_To_Hex (T : in out Test); procedure Test_Measure_Copy (T : in out Test); procedure Test_Index (T : in out Test); procedure Test_Rindex (T : in out Test); -- Do some benchmark on String -> X hash mapped. procedure Test_Measure_Hash (T : in out Test); -- Test String_Ref creation procedure Test_String_Ref (T : in out Test); -- Benchmark comparison between the use of Iterate vs Query_Element. procedure Test_Perf_Vector (T : in out Test); -- Test perfect hash (samples/gperfhash) procedure Test_Perfect_Hash (T : in out Test); -- Test the token iteration. procedure Test_Iterate_Token (T : in out Test); end Util.Strings.Tests;
Declare the Test_Perf_Vector procedure for some performance measurement
Declare the Test_Perf_Vector procedure for some performance measurement
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
866a5d92339052c322a6aee8463f2c4ebfafdf1d
regtests/wiki-writers-tests.adb
regtests/wiki-writers-tests.adb
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Ada.Characters.Conversions; with Util.Files; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Filters.Html; with Wiki.Writers.Builders; with Wiki.Utils; package body Wiki.Writers.Tests is use Ada.Strings.Unbounded; use type Wiki.Parsers.Wiki_Syntax_Type; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Result_File : constant String := To_String (T.Result); Content : Unbounded_String; begin Util.Files.Read_File (Path => To_String (T.File), Into => Content, Max_Size => 10000); declare Time : Util.Measures.Stamp; begin if T.Source = Wiki.Parsers.SYNTAX_HTML then declare Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access, T.Format); Html_Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide (To_String (Content)), Wiki.Parsers.SYNTAX_HTML); Content := To_Unbounded_String (Writer.To_String); end; elsif T.Is_Html then Content := To_Unbounded_String (Utils.To_Html (To_Wide (To_String (Content)), T.Format)); else Content := To_Unbounded_String (Utils.To_Text (To_Wide (To_String (Content)), T.Format)); end if; Util.Measures.Report (Time, "Render " & To_String (T.Name)); end; Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.Parsers.SYNTAX_HTML then return Util.Tests.Format ("Test IMPORT " & To_String (T.Name)); elsif T.Is_Html then return Util.Tests.Format ("Test HTML " & To_String (T.Name)); else return Util.Tests.Format ("Test TEXT " & To_String (T.Name)); end if; end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Render; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access; Result_Dir : constant String := "regtests/result"; Expect_Dir : constant String := "regtests/expect"; 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 : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access is Tst : Test_Case_Access; begin Tst := new Test; Tst.Is_Html := Is_Html; Tst.Name := To_Unbounded_String (Name); Tst.File := To_Unbounded_String (Path); Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name); Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name); Tst.Format := Format; Tst.Source := Format; return Tst; end Create_Test; procedure Add_Wiki_Tests is Dir : constant String := "regtests/files/wiki"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Ext : constant String := Ada.Directories.Extension (Simple); Tst : Test_Case_Access; Format : Wiki.Parsers.Wiki_Syntax_Type; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.Parsers.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.Parsers.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.Parsers.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.Parsers.SYNTAX_MEDIA_WIKI; else Format := Wiki.Parsers.SYNTAX_MIX; end if; Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True); Suite.Add_Test (Tst.all'Access); Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Wiki_Tests; procedure Add_Import_Tests is Dir : constant String := "regtests/files/html"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Name : constant String := Base_Name (Simple); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then for Syntax in Wiki.Parsers.Wiki_Syntax_Type'Range loop case Syntax is when Wiki.Parsers.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.Parsers.SYNTAX_DOTCLEAR => Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.Parsers.SYNTAX_MEDIA_WIKI => Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple, Syntax, "/wiki-import/", True); when others => Tst := null; end case; if Tst /= null then Tst.Source := Wiki.Parsers.SYNTAX_HTML; Suite.Add_Test (Tst.all'Access); end if; end loop; end if; end; end loop; end Add_Import_Tests; begin Add_Wiki_Tests; Add_Import_Tests; end Add_Tests; end Wiki.Writers.Tests;
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Ada.Characters.Conversions; with Util.Files; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Filters.Html; with Wiki.Writers.Builders; with Wiki.Utils; package body Wiki.Writers.Tests is use Ada.Strings.Unbounded; use type Wiki.Parsers.Wiki_Syntax_Type; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Result_File : constant String := To_String (T.Result); Content : Unbounded_String; begin Util.Files.Read_File (Path => To_String (T.File), Into => Content, Max_Size => 10000); declare Time : Util.Measures.Stamp; begin if T.Source = Wiki.Parsers.SYNTAX_HTML then declare Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access, T.Format); Html_Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide (To_String (Content)), Wiki.Parsers.SYNTAX_HTML); Content := To_Unbounded_String (Writer.To_String); end; elsif T.Is_Html then Content := To_Unbounded_String (Utils.To_Html (To_Wide (To_String (Content)), T.Format)); else Content := To_Unbounded_String (Utils.To_Text (To_Wide (To_String (Content)), T.Format)); end if; Util.Measures.Report (Time, "Render " & To_String (T.Name)); end; Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.Parsers.SYNTAX_HTML then return Util.Tests.Format ("Test IMPORT " & To_String (T.Name)); elsif T.Is_Html then return Util.Tests.Format ("Test HTML " & To_String (T.Name)); else return Util.Tests.Format ("Test TEXT " & To_String (T.Name)); end if; end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Render; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; procedure Add_Import_Tests; procedure Add_Wiki_Tests; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access; Result_Dir : constant String := "regtests/result"; Expect_Dir : constant String := "regtests/expect"; 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 : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access is Tst : Test_Case_Access; begin Tst := new Test; Tst.Is_Html := Is_Html; Tst.Name := To_Unbounded_String (Name); Tst.File := To_Unbounded_String (Path); Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name); Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name); Tst.Format := Format; Tst.Source := Format; return Tst; end Create_Test; procedure Add_Wiki_Tests is Dir : constant String := "regtests/files/wiki"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Ext : constant String := Ada.Directories.Extension (Simple); Tst : Test_Case_Access; Format : Wiki.Parsers.Wiki_Syntax_Type; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.Parsers.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.Parsers.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.Parsers.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.Parsers.SYNTAX_MEDIA_WIKI; else Format := Wiki.Parsers.SYNTAX_MIX; end if; Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True); Suite.Add_Test (Tst.all'Access); Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Wiki_Tests; procedure Add_Import_Tests is Dir : constant String := "regtests/files/html"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Name : constant String := Base_Name (Simple); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then for Syntax in Wiki.Parsers.Wiki_Syntax_Type'Range loop case Syntax is when Wiki.Parsers.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.Parsers.SYNTAX_DOTCLEAR => Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.Parsers.SYNTAX_MEDIA_WIKI => Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple, Syntax, "/wiki-import/", True); when others => Tst := null; end case; if Tst /= null then Tst.Source := Wiki.Parsers.SYNTAX_HTML; Suite.Add_Test (Tst.all'Access); end if; end loop; end if; end; end loop; end Add_Import_Tests; begin Add_Wiki_Tests; Add_Import_Tests; end Add_Tests; end Wiki.Writers.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
03bd18a8915570eff489a73be0b33012b847fe11
src/wiki-render-text.adb
src/wiki-render-text.adb
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Helpers; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Document : in out Text_Renderer; Level : in Natural) is begin Document.Close_Paragraph; for I in 1 .. Level loop Document.Output.Write (" "); end loop; end Add_Blockquote; -- ------------------------------ -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Render_List_Item (Engine : in out Text_Renderer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; end Render_List_Item; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Document : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is begin Document.Open_Paragraph; if Title'Length /= 0 then Document.Output.Write (Title); end if; Document.Empty_Line := False; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); begin Document.Open_Paragraph; -- if Length (Alt) > 0 then -- Document.Output.Write (Alt); -- end if; -- if Length (Description) > 0 then -- Document.Output.Write (Description); -- end if; -- Document.Output.Write (Link); Document.Empty_Line := False; end Add_Image; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Text_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Format); begin Document.Close_Paragraph; -- Document.Output.Write (Text); Document.Empty_Line := False; end Add_Preformatted; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Output.Write (Node.Header); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_LIST => Engine.Render_List_Item (Node.Level, False); when Wiki.Nodes.N_NUM_LIST => Engine.Render_List_Item (Node.Level, True); when Wiki.Nodes.N_TEXT => if Engine.Empty_Line and Engine.Indent_Level /= 0 then for I in 1 .. Engine.Indent_Level loop Engine.Output.Write (' '); end loop; end if; Engine.Output.Write (Node.Text); Engine.Empty_Line := False; when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Add_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_BLOCKQUOTE => null; when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.Nodes.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.Nodes.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.Nodes.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Text_Renderer) is begin Document.Close_Paragraph; end Finish; end Wiki.Render.Text;
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Helpers; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; -- ------------------------------ -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Render_List_Item (Engine : in out Text_Renderer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; end Render_List_Item; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Document : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is begin Document.Open_Paragraph; if Title'Length /= 0 then Document.Output.Write (Title); end if; Document.Empty_Line := False; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); begin Document.Open_Paragraph; -- if Length (Alt) > 0 then -- Document.Output.Write (Alt); -- end if; -- if Length (Description) > 0 then -- Document.Output.Write (Description); -- end if; -- Document.Output.Write (Link); Document.Empty_Line := False; end Add_Image; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Output.Write (Node.Header); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST => Engine.Render_List_Item (Node.Level, False); when Wiki.Nodes.N_NUM_LIST => Engine.Render_List_Item (Node.Level, True); when Wiki.Nodes.N_TEXT => if Engine.Empty_Line and Engine.Indent_Level /= 0 then for I in 1 .. Engine.Indent_Level loop Engine.Output.Write (' '); end loop; end if; Engine.Output.Write (Node.Text); Engine.Empty_Line := False; when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Add_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.Nodes.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.Nodes.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.Nodes.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Text_Renderer) is begin Document.Close_Paragraph; end Finish; end Wiki.Render.Text;
Update Render_Preformatted and Render_Blockquote operations for the xnew document model
Update Render_Preformatted and Render_Blockquote operations for the xnew document model
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
22597a5ba6b56835788022d77948f7d0e10844bd
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with ADO; with Security.Contexts; with AWA.Services.Contexts; with AWA.Storages.Modules; with AWA.Storages.Beans.Factories; with AWA.Tests.Helpers.Users; package body AWA.Storages.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Storages.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save", Test_Create_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete", Test_Delete_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean", Test_Create_Folder'Access); end Add_Tests; -- ------------------------------ -- Save something in a storage element and keep track of the store id in the test <b>Id</b>. -- ------------------------------ procedure Save (T : in out Test) is Store : AWA.Storages.Models.Storage_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Save (Into => Store, Path => "Makefile", Storage => AWA.Storages.Models.DATABASE); T.Assert (not Store.Is_Null, "Storage object should not be null"); T.Id := Store.Get_Id; T.Assert (T.Id > 0, "Invalid storage identifier"); end Save; -- ------------------------------ -- Load the storage element refered to by the test <b>Id</b>. -- ------------------------------ procedure Load (T : in out Test) is use type Ada.Streams.Stream_Element_Offset; Data : ADO.Blob_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Load (From => T.Id, Into => Data); T.Assert (not Data.Is_Null, "Null blob returned by load"); T.Assert (Data.Value.Len > 100, "Invalid length for the blob data"); end Load; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Load; end Test_Create_Storage; -- ------------------------------ -- Test deletion of a storage object -- ------------------------------ procedure Test_Delete_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Data : ADO.Blob_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Manager.Delete (T.Id); T.Manager.Load (From => T.Id, Into => Data); T.Assert (Data.Is_Null, "A non null blob returned by load"); end Test_Delete_Storage; -- ------------------------------ -- Test creation of a storage folder -- ------------------------------ procedure Test_Create_Folder (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Folder : AWA.Storages.Beans.Factories.Folder_Bean; Outcome : Ada.Strings.Unbounded.Unbounded_String; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Folder.Set_Name ("Test folder name"); Folder.Module := AWA.Storages.Modules.Get_Storage_Module; Folder.Save (Outcome); Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action"); end Test_Create_Folder; end AWA.Storages.Services.Tests;
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with ADO; with Security.Contexts; with AWA.Services.Contexts; with AWA.Storages.Modules; with AWA.Storages.Beans.Factories; with AWA.Tests.Helpers.Users; package body AWA.Storages.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Storages.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save", Test_Create_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete", Test_Delete_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean", Test_Create_Folder'Access); end Add_Tests; -- ------------------------------ -- Save something in a storage element and keep track of the store id in the test <b>Id</b>. -- ------------------------------ procedure Save (T : in out Test) is Store : AWA.Storages.Models.Storage_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Save (Into => Store, Path => "Makefile", Storage => AWA.Storages.Models.DATABASE); T.Assert (not Store.Is_Null, "Storage object should not be null"); T.Id := Store.Get_Id; T.Assert (T.Id > 0, "Invalid storage identifier"); end Save; -- ------------------------------ -- Load the storage element refered to by the test <b>Id</b>. -- ------------------------------ procedure Load (T : in out Test) is use type Ada.Streams.Stream_Element_Offset; Mime : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; Data : ADO.Blob_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Load (From => T.Id, Mime => Mime, Date => Date, Into => Data); T.Assert (not Data.Is_Null, "Null blob returned by load"); T.Assert (Data.Value.Len > 100, "Invalid length for the blob data"); end Load; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Load; end Test_Create_Storage; -- ------------------------------ -- Test deletion of a storage object -- ------------------------------ procedure Test_Delete_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Data : ADO.Blob_Ref; Mime : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Manager.Delete (T.Id); T.Manager.Load (From => T.Id, Mime => Mime, Date => Date, Into => Data); T.Assert (Data.Is_Null, "A non null blob returned by load"); end Test_Delete_Storage; -- ------------------------------ -- Test creation of a storage folder -- ------------------------------ procedure Test_Create_Folder (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Folder : AWA.Storages.Beans.Factories.Folder_Bean; Outcome : Ada.Strings.Unbounded.Unbounded_String; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Folder.Set_Name ("Test folder name"); Folder.Module := AWA.Storages.Modules.Get_Storage_Module; Folder.Save (Outcome); Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action"); end Test_Create_Folder; end AWA.Storages.Services.Tests;
Update the unit test
Update the unit test
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
d26f95c8b01338ce7fa7f7e14db72b88fbad2356
awa/plugins/awa-changelogs/regtests/awa-changelogs-modules-tests.ads
awa/plugins/awa-changelogs/regtests/awa-changelogs-modules-tests.ads
----------------------------------------------------------------------- -- awa-changelogs-tests -- Tests for changelogs -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package AWA.Changelogs.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Add_Log (T : in out Test); end AWA.Changelogs.Modules.Tests;
----------------------------------------------------------------------- -- awa-changelogs-tests -- Tests for changelogs -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; package AWA.Changelogs.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with null record; procedure Test_Add_Log (T : in out Test); end AWA.Changelogs.Modules.Tests;
Fix the unit test to use AWA.Tests.Test for the correct test setup
Fix the unit test to use AWA.Tests.Test for the correct test setup
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1ce636fa86fa73ade8f407355b44d928271f495c
tools/druss-commands-bboxes.ads
tools/druss-commands-bboxes.ads
----------------------------------------------------------------------- -- druss-commands-bboxes -- Commands to manage the bboxes -- 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.Bboxes is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; procedure Discover (Command : in Command_Type); -- Execute the command with the arguments. The command name is passed with the command -- arguments. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Druss.Commands.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.Bboxes;
----------------------------------------------------------------------- -- druss-commands-bboxes -- Commands to manage the bboxes -- 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.Bboxes is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; procedure Discover (Command : in Command_Type; Context : in out Context_Type); -- Add the bbox with the given IP address. procedure Add_Bbox (Command : in Command_Type; IP : in String; Context : in out Context_Type); -- Execute the command with the arguments. The command name is passed with the command -- arguments. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Druss.Commands.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.Bboxes;
Declare the Add_Bbox procedure to add an IP address to the configuration Add the context to the Discover procedure
Declare the Add_Bbox procedure to add an IP address to the configuration Add the context to the Discover procedure
Ada
apache-2.0
stcarrez/bbox-ada-api
f9ba75acdfc993b5379c417e440fc1c63e22bbc2
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Services.Contexts; with AWA.Storages.Modules; with AWA.Storages.Beans.Factories; with AWA.Tests.Helpers.Users; package body AWA.Storages.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Storages.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save", Test_Create_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete", Test_Delete_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean", Test_Create_Folder'Access); end Add_Tests; -- ------------------------------ -- Save something in a storage element and keep track of the store id in the test <b>Id</b>. -- ------------------------------ procedure Save (T : in out Test) is Store : AWA.Storages.Models.Storage_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Save (Into => Store, Path => "Makefile", Storage => AWA.Storages.Models.DATABASE); T.Assert (not Store.Is_Null, "Storage object should not be null"); T.Id := Store.Get_Id; T.Assert (T.Id > 0, "Invalid storage identifier"); end Save; -- ------------------------------ -- Load the storage element refered to by the test <b>Id</b>. -- ------------------------------ procedure Load (T : in out Test) is use type Ada.Streams.Stream_Element_Offset; Name : Ada.Strings.Unbounded.Unbounded_String; Mime : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; Data : ADO.Blob_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data); T.Assert (not Data.Is_Null, "Null blob returned by load"); T.Assert (Data.Value.Len > 100, "Invalid length for the blob data"); end Load; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Load; end Test_Create_Storage; -- ------------------------------ -- Test deletion of a storage object -- ------------------------------ procedure Test_Delete_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Data : ADO.Blob_Ref; Name : Ada.Strings.Unbounded.Unbounded_String; Mime : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Manager.Delete (T.Id); T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data); T.Assert (Data.Is_Null, "A non null blob returned by load"); end Test_Delete_Storage; -- ------------------------------ -- Test creation of a storage folder -- ------------------------------ procedure Test_Create_Folder (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Folder : AWA.Storages.Beans.Factories.Folder_Bean; Outcome : Ada.Strings.Unbounded.Unbounded_String; Folder2 : AWA.Storages.Beans.Factories.Folder_Bean; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Folder.Set_Name ("Test folder name"); Folder.Module := AWA.Storages.Modules.Get_Storage_Module; Folder.Save (Outcome); Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action"); Folder2.Set_Value ("folderId", ADO.Objects.To_Object (Folder.Get_Key)); Util.Tests.Assert_Equals (T, "Test folder name", String '(Folder2.Get_Name), "Invalid folder name"); end Test_Create_Folder; end AWA.Storages.Services.Tests;
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Services.Contexts; with AWA.Storages.Modules; with AWA.Storages.Beans.Factories; with AWA.Tests.Helpers.Users; package body AWA.Storages.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Storages.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save", Test_Create_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete", Test_Delete_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean", Test_Create_Folder'Access); end Add_Tests; -- ------------------------------ -- Save something in a storage element and keep track of the store id in the test <b>Id</b>. -- ------------------------------ procedure Save (T : in out Test) is Store : AWA.Storages.Models.Storage_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Save (Into => Store, Path => "Makefile", Storage => AWA.Storages.Models.DATABASE); T.Assert (not Store.Is_Null, "Storage object should not be null"); T.Id := Store.Get_Id; T.Assert (T.Id > 0, "Invalid storage identifier"); end Save; -- ------------------------------ -- Load the storage element refered to by the test <b>Id</b>. -- ------------------------------ procedure Load (T : in out Test) is use type Ada.Streams.Stream_Element_Offset; Name : Ada.Strings.Unbounded.Unbounded_String; Mime : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; Data : ADO.Blob_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data); T.Assert (not Data.Is_Null, "Null blob returned by load"); T.Assert (Data.Value.Len > 100, "Invalid length for the blob data"); end Load; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Load; end Test_Create_Storage; -- ------------------------------ -- Test deletion of a storage object -- ------------------------------ procedure Test_Delete_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Data : ADO.Blob_Ref; Name : Ada.Strings.Unbounded.Unbounded_String; Mime : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Manager.Delete (T.Id); begin T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data); T.Assert (False, "No exception raised"); exception when ADO.Objects.NOT_FOUND => null; end; end Test_Delete_Storage; -- ------------------------------ -- Test creation of a storage folder -- ------------------------------ procedure Test_Create_Folder (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Folder : AWA.Storages.Beans.Factories.Folder_Bean; Outcome : Ada.Strings.Unbounded.Unbounded_String; Upload : AWA.Storages.Beans.Factories.Upload_Bean; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Folder.Module := AWA.Storages.Modules.Get_Storage_Module; Upload.Module := AWA.Storages.Modules.Get_Storage_Module; Folder.Set_Name ("Test folder name"); Folder.Save (Outcome); Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action"); Upload.Set_Value ("folderId", ADO.Objects.To_Object (Folder.Get_Key)); Util.Tests.Assert_Equals (T, "Test folder name", String '(Upload.Get_Folder.Get_Name), "Invalid folder name"); end Test_Create_Folder; end AWA.Storages.Services.Tests;
Fix storage unit test
Fix storage unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
84329c9382dabc5ff2405553fa13d3d7418fe0d6
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); 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; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Filter : in out Image_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is Src : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attributes, "src"); begin Add_String (Filter.Items, Src); Filter_Type (Filter).Add_Image (Document, Name, Attributes); end Add_Image; end Wiki.Filters.Collectors;
----------------------------------------------------------------------- -- wiki-filters-collectors -- Wiki word and link collectors -- Copyright (C) 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- 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; procedure Collect_Attribute (Filter : in out Collector_Type; Attributes : in Wiki.Attributes.Attribute_List; Name : in String) is Value : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attributes, Name); begin if Value'Length > 0 then Add_String (Filter.Items, Value); end if; end Collect_Attribute; -- ------------------------------ -- 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; -- ------------------------------ -- 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_Attribute (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_Attribute (Filter, Attributes, "href"); end if; Filter_Type (Filter).Push_Node (Document, Tag, Attributes); end Push_Node; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Filter : in out Image_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Collect_Attribute (Filter, Attributes, "src"); Filter_Type (Filter).Add_Image (Document, Name, Attributes); end Add_Image; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ overriding procedure Push_Node (Filter : in out Image_Collector_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Tag = IMG_TAG then Collect_Attribute (Filter, Attributes, "src"); end if; Filter_Type (Filter).Push_Node (Document, Tag, Attributes); end Push_Node; end Wiki.Filters.Collectors;
Update the Image_Collector_Type to recognize the <img> elements
Update the Image_Collector_Type to recognize the <img> elements
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
4f8b7b533f4c450eb08f5e18dc87b57183552719
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; package body ADO.Drivers.Connections is use Util.Log; use Ada.Strings.Fixed; Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers.Connections"); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 > Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); Controller.Port := Integer'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Integer is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin Log.Info ("Get driver {0}", Name); while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Util.Log; use Ada.Strings.Fixed; Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers.Connections"); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 > Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); Controller.Port := Integer'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Integer is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; type Driver_Initialize_Access is not null access procedure; procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 1 loop if Retry > 0 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
Add support to load database drivers dynamically - extract the driver name from the connection string, - load the DLL, - find the driver initialization method and call it
Add support to load database drivers dynamically - extract the driver name from the connection string, - load the DLL, - find the driver initialization method and call it
Ada
apache-2.0
Letractively/ada-ado
3e607a5913827e29bcc8c17ab928948e2b5d04da
src/natools-smaz.adb
src/natools-smaz.adb
------------------------------------------------------------------------------ -- Copyright (c) 2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz is use type Ada.Streams.Stream_Element_Offset; procedure Find_Entry (Dict : in Dictionary; Template : in String; Index : out Ada.Streams.Stream_Element; Length : out Natural); -- Try to find the longest entry in Dict that is a prefix of Template, -- setting Length to 0 when no such entry exists. function To_String (Data : in Ada.Streams.Stream_Element_Array) return String; -- Convert a stream element array into a string function Verbatim_Size (Dict : Dictionary; Original_Size : Natural) return Ada.Streams.Stream_Element_Count; -- Return the number of bytes needed by the verbatim encoding -- of Original_Size bytes. ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Find_Entry (Dict : in Dictionary; Template : in String; Index : out Ada.Streams.Stream_Element; Length : out Natural) is I : Ada.Streams.Stream_Element; N : Natural; begin Index := Ada.Streams.Stream_Element'Last; Length := 0; for Last in reverse Template'Range loop N := Dict.Hash (Template (Template'First .. Last)); if N <= Natural (Dict.Dict_Last) then I := Ada.Streams.Stream_Element (N); if Dict_Entry (Dict, I) = Template (Template'First .. Last) then Index := I; Length := 1 + Last - Template'First; return; end if; end if; end loop; end Find_Entry; function To_String (Data : in Ada.Streams.Stream_Element_Array) return String is begin return Result : String (1 .. Data'Length) do for I in Result'Range loop Result (I) := Character'Val (Data (Data'First + Ada.Streams.Stream_Element_Offset (I - 1))); end loop; end return; end To_String; function Verbatim_Size (Dict : Dictionary; Original_Size : Natural) return Ada.Streams.Stream_Element_Count is Verbatim1_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last - Dict.Dict_Last) - Boolean'Pos (Dict.Variable_Length_Verbatim); Verbatim2_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Remaining : Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Original_Size); Overhead : Ada.Streams.Stream_Element_Count := 0; begin if Dict.Variable_Length_Verbatim then if Remaining >= Verbatim2_Max_Size then declare Full_Blocks : constant Ada.Streams.Stream_Element_Count := Remaining / Verbatim2_Max_Size; begin Overhead := Overhead + 2 * Full_Blocks; Remaining := Remaining - Verbatim2_Max_Size * Full_Blocks; end; end if; if Remaining > Verbatim1_Max_Size then Overhead := Overhead + 2; Remaining := 0; end if; end if; declare Full_Blocks : constant Ada.Streams.Stream_Element_Count := Remaining / Verbatim1_Max_Size; begin Overhead := Overhead + Full_Blocks; end; return Overhead + Ada.Streams.Stream_Element_Count (Original_Size); end Verbatim_Size; ---------------------- -- Public Interface -- ---------------------- function Dict_Entry (Dict : in Dictionary; Index : in Ada.Streams.Stream_Element) return String is First : constant Positive := Dict.Offsets (Index); Last : Natural := Dict.Values'Last; begin if Index + 1 in Dict.Offsets'Range then Last := Dict.Offsets (Index + 1) - 1; end if; return Dict.Values (First .. Last); end Dict_Entry; function Compressed_Upper_Bound (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Count is begin return Verbatim_Size (Dict, Input'Length); end Compressed_Upper_Bound; procedure Compress (Dict : in Dictionary; Input : in String; Output_Buffer : out Ada.Streams.Stream_Element_Array; Output_Last : out Ada.Streams.Stream_Element_Offset) is procedure Find_Entry; Verbatim1_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last - Dict.Dict_Last) - Boolean'Pos (Dict.Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Input_Index : Positive := Input'First; Length : Natural; Word : Ada.Streams.Stream_Element; procedure Find_Entry is begin Find_Entry (Dict, Input (Input_Index .. Natural'Min (Input_Index + Dict.Max_Word_Length - 1, Input'Last)), Word, Length); end Find_Entry; Previous_Verbatim_Beginning : Natural := 0; Previous_Verbatim_Last : Ada.Streams.Stream_Element_Offset := 0; begin Output_Last := Output_Buffer'First - 1; Find_Entry; Main_Loop : while Input_Index in Input'Range loop Data_In_Dict : while Length > 0 loop Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Word; Input_Index := Input_Index + Length; exit Main_Loop when Input_Index not in Input'Range; Find_Entry; end loop Data_In_Dict; Verbatim_Block : declare Beginning : Positive := Input_Index; Verbatim_Length, Block_Length : Natural; begin Verbatim_Scan : while Length = 0 and Input_Index in Input'Range loop Input_Index := Input_Index + 1; Find_Entry; end loop Verbatim_Scan; Verbatim_Length := Input_Index - Beginning; if Previous_Verbatim_Beginning > 0 and then Output_Last + Verbatim_Size (Dict, Verbatim_Length) >= Previous_Verbatim_Last + Verbatim_Size (Dict, Input_Index - Previous_Verbatim_Beginning) then Beginning := Previous_Verbatim_Beginning; Output_Last := Previous_Verbatim_Last; Verbatim_Length := Input_Index - Beginning; else Previous_Verbatim_Beginning := Beginning; Previous_Verbatim_Last := Output_Last; end if; Verbatim_Encode : while Verbatim_Length > 0 loop if Dict.Variable_Length_Verbatim and then Verbatim_Length > Verbatim1_Max_Size then Block_Length := Natural'Min (Verbatim_Length, Verbatim2_Max_Size); Output_Buffer (Output_Last + 1) := Ada.Streams.Stream_Element'Last; Output_Buffer (Output_Last + 2) := Ada.Streams.Stream_Element (Block_Length - Verbatim1_Max_Size); Output_Last := Output_Last + 2; else Block_Length := Natural'Min (Verbatim_Length, Verbatim1_Max_Size); Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Ada.Streams.Stream_Element'Last - Ada.Streams.Stream_Element (Block_Length - 1 + Boolean'Pos (Dict.Variable_Length_Verbatim)); end if; Verbatim_Copy : for I in Beginning .. Beginning + Block_Length - 1 loop Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Character'Pos (Input (I)); end loop Verbatim_Copy; Verbatim_Length := Verbatim_Length - Block_Length; Beginning := Beginning + Block_Length; end loop Verbatim_Encode; end Verbatim_Block; end loop Main_Loop; end Compress; function Compress (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Array is Result : Ada.Streams.Stream_Element_Array (1 .. Compressed_Upper_Bound (Dict, Input)); Last : Ada.Streams.Stream_Element_Offset; begin Compress (Dict, Input, Result, Last); return Result (Result'First .. Last); end Compress; function Decompressed_Length (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return Natural is Result : Natural := 0; Verbatim_Code_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Dict.Dict_Last); Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Input_Byte : Ada.Streams.Stream_Element; Verbatim_Length : Ada.Streams.Stream_Element_Offset; begin while Input_Index in Input'Range loop Input_Byte := Input (Input_Index); if Input_Byte in Dict.Offsets'Range then Result := Result + Dict_Entry (Dict, Input_Byte)'Length; Input_Index := Input_Index + 1; else if not Dict.Variable_Length_Verbatim then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte) + 1; elsif Input_Byte < Ada.Streams.Stream_Element'Last then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte); else Input_Index := Input_Index + 1; Verbatim_Length := Ada.Streams.Stream_Element_Offset (Input (Input_Index)) + Verbatim_Code_Count - 1; end if; Result := Result + Positive (Verbatim_Length); Input_Index := Input_Index + Verbatim_Length + 1; end if; end loop; return Result; end Decompressed_Length; procedure Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array; Output_Buffer : out String; Output_Last : out Natural) is procedure Append (S : in String); procedure Append (S : in Ada.Streams.Stream_Element_Array); procedure Append (S : in String) is begin Output_Buffer (Output_Last + 1 .. Output_Last + S'Length) := S; Output_Last := Output_Last + S'Length; end Append; procedure Append (S : in Ada.Streams.Stream_Element_Array) is begin Append (To_String (S)); end Append; Verbatim_Code_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Dict.Dict_Last); Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Input_Byte : Ada.Streams.Stream_Element; Verbatim_Length : Ada.Streams.Stream_Element_Offset; begin Output_Last := Output_Buffer'First - 1; while Input_Index in Input'Range loop Input_Byte := Input (Input_Index); if Input_Byte in Dict.Offsets'Range then Append (Dict_Entry (Dict, Input_Byte)); Input_Index := Input_Index + 1; else if not Dict.Variable_Length_Verbatim then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte) + 1; elsif Input_Byte < Ada.Streams.Stream_Element'Last then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte); else Input_Index := Input_Index + 1; Verbatim_Length := Ada.Streams.Stream_Element_Offset (Input (Input_Index)) + Verbatim_Code_Count - 1; end if; Append (Input (Input_Index + 1 .. Input_Index + Verbatim_Length)); Input_Index := Input_Index + Verbatim_Length + 1; end if; end loop; end Decompress; function Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return String is Result : String (1 .. Decompressed_Length (Dict, Input)); Last : Natural; begin Decompress (Dict, Input, Result, Last); pragma Assert (Last = Result'Last); return Result; end Decompress; end Natools.Smaz;
------------------------------------------------------------------------------ -- Copyright (c) 2016-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz is use type Ada.Streams.Stream_Element_Offset; procedure Find_Entry (Dict : in Dictionary; Template : in String; Index : out Ada.Streams.Stream_Element; Length : out Natural); -- Try to find the longest entry in Dict that is a prefix of Template, -- setting Length to 0 when no such entry exists. function To_String (Data : in Ada.Streams.Stream_Element_Array) return String; -- Convert a stream element array into a string function Verbatim_Size (Dict : Dictionary; Original_Size : Natural) return Ada.Streams.Stream_Element_Count; -- Return the number of bytes needed by the verbatim encoding -- of Original_Size bytes. ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Find_Entry (Dict : in Dictionary; Template : in String; Index : out Ada.Streams.Stream_Element; Length : out Natural) is I : Ada.Streams.Stream_Element; N : Natural; begin Index := Ada.Streams.Stream_Element'Last; Length := 0; for Last in reverse Template'Range loop N := Dict.Hash (Template (Template'First .. Last)); if N <= Natural (Dict.Dict_Last) then I := Ada.Streams.Stream_Element (N); if Dict_Entry (Dict, I) = Template (Template'First .. Last) then Index := I; Length := 1 + Last - Template'First; return; end if; end if; end loop; end Find_Entry; function To_String (Data : in Ada.Streams.Stream_Element_Array) return String is begin return Result : String (1 .. Data'Length) do for I in Result'Range loop Result (I) := Character'Val (Data (Data'First + Ada.Streams.Stream_Element_Offset (I - 1))); end loop; end return; end To_String; function Verbatim_Size (Dict : Dictionary; Original_Size : Natural) return Ada.Streams.Stream_Element_Count is Verbatim1_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last - Dict.Dict_Last) - Boolean'Pos (Dict.Variable_Length_Verbatim); Verbatim2_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Remaining : Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Original_Size); Overhead : Ada.Streams.Stream_Element_Count := 0; begin if Dict.Variable_Length_Verbatim then if Remaining >= Verbatim2_Max_Size then declare Full_Blocks : constant Ada.Streams.Stream_Element_Count := Remaining / Verbatim2_Max_Size; begin Overhead := Overhead + 2 * Full_Blocks; Remaining := Remaining - Verbatim2_Max_Size * Full_Blocks; end; end if; if Remaining > Verbatim1_Max_Size then Overhead := Overhead + 2; Remaining := 0; end if; end if; declare Block_Count : constant Ada.Streams.Stream_Element_Count := (Remaining + Verbatim1_Max_Size - 1) / Verbatim1_Max_Size; begin Overhead := Overhead + Block_Count; end; return Overhead + Ada.Streams.Stream_Element_Count (Original_Size); end Verbatim_Size; ---------------------- -- Public Interface -- ---------------------- function Dict_Entry (Dict : in Dictionary; Index : in Ada.Streams.Stream_Element) return String is First : constant Positive := Dict.Offsets (Index); Last : Natural := Dict.Values'Last; begin if Index + 1 in Dict.Offsets'Range then Last := Dict.Offsets (Index + 1) - 1; end if; return Dict.Values (First .. Last); end Dict_Entry; function Compressed_Upper_Bound (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Count is begin return Verbatim_Size (Dict, Input'Length); end Compressed_Upper_Bound; procedure Compress (Dict : in Dictionary; Input : in String; Output_Buffer : out Ada.Streams.Stream_Element_Array; Output_Last : out Ada.Streams.Stream_Element_Offset) is procedure Find_Entry; Verbatim1_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last - Dict.Dict_Last) - Boolean'Pos (Dict.Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Input_Index : Positive := Input'First; Length : Natural; Word : Ada.Streams.Stream_Element; procedure Find_Entry is begin Find_Entry (Dict, Input (Input_Index .. Natural'Min (Input_Index + Dict.Max_Word_Length - 1, Input'Last)), Word, Length); end Find_Entry; Previous_Verbatim_Beginning : Natural := 0; Previous_Verbatim_Last : Ada.Streams.Stream_Element_Offset := 0; begin Output_Last := Output_Buffer'First - 1; Find_Entry; Main_Loop : while Input_Index in Input'Range loop Data_In_Dict : while Length > 0 loop Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Word; Input_Index := Input_Index + Length; exit Main_Loop when Input_Index not in Input'Range; Find_Entry; end loop Data_In_Dict; Verbatim_Block : declare Beginning : Positive := Input_Index; Verbatim_Length, Block_Length : Natural; begin Verbatim_Scan : while Length = 0 and Input_Index in Input'Range loop Input_Index := Input_Index + 1; Find_Entry; end loop Verbatim_Scan; Verbatim_Length := Input_Index - Beginning; if Previous_Verbatim_Beginning > 0 and then Output_Last + Verbatim_Size (Dict, Verbatim_Length) >= Previous_Verbatim_Last + Verbatim_Size (Dict, Input_Index - Previous_Verbatim_Beginning) then Beginning := Previous_Verbatim_Beginning; Output_Last := Previous_Verbatim_Last; Verbatim_Length := Input_Index - Beginning; else Previous_Verbatim_Beginning := Beginning; Previous_Verbatim_Last := Output_Last; end if; Verbatim_Encode : while Verbatim_Length > 0 loop if Dict.Variable_Length_Verbatim and then Verbatim_Length > Verbatim1_Max_Size then Block_Length := Natural'Min (Verbatim_Length, Verbatim2_Max_Size); Output_Buffer (Output_Last + 1) := Ada.Streams.Stream_Element'Last; Output_Buffer (Output_Last + 2) := Ada.Streams.Stream_Element (Block_Length - Verbatim1_Max_Size); Output_Last := Output_Last + 2; else Block_Length := Natural'Min (Verbatim_Length, Verbatim1_Max_Size); Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Ada.Streams.Stream_Element'Last - Ada.Streams.Stream_Element (Block_Length - 1 + Boolean'Pos (Dict.Variable_Length_Verbatim)); end if; Verbatim_Copy : for I in Beginning .. Beginning + Block_Length - 1 loop Output_Last := Output_Last + 1; Output_Buffer (Output_Last) := Character'Pos (Input (I)); end loop Verbatim_Copy; Verbatim_Length := Verbatim_Length - Block_Length; Beginning := Beginning + Block_Length; end loop Verbatim_Encode; end Verbatim_Block; end loop Main_Loop; end Compress; function Compress (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Array is Result : Ada.Streams.Stream_Element_Array (1 .. Compressed_Upper_Bound (Dict, Input)); Last : Ada.Streams.Stream_Element_Offset; begin Compress (Dict, Input, Result, Last); return Result (Result'First .. Last); end Compress; function Decompressed_Length (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return Natural is Result : Natural := 0; Verbatim_Code_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Dict.Dict_Last); Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Input_Byte : Ada.Streams.Stream_Element; Verbatim_Length : Ada.Streams.Stream_Element_Offset; begin while Input_Index in Input'Range loop Input_Byte := Input (Input_Index); if Input_Byte in Dict.Offsets'Range then Result := Result + Dict_Entry (Dict, Input_Byte)'Length; Input_Index := Input_Index + 1; else if not Dict.Variable_Length_Verbatim then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte) + 1; elsif Input_Byte < Ada.Streams.Stream_Element'Last then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte); else Input_Index := Input_Index + 1; Verbatim_Length := Ada.Streams.Stream_Element_Offset (Input (Input_Index)) + Verbatim_Code_Count - 1; end if; Result := Result + Positive (Verbatim_Length); Input_Index := Input_Index + Verbatim_Length + 1; end if; end loop; return Result; end Decompressed_Length; procedure Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array; Output_Buffer : out String; Output_Last : out Natural) is procedure Append (S : in String); procedure Append (S : in Ada.Streams.Stream_Element_Array); procedure Append (S : in String) is begin Output_Buffer (Output_Last + 1 .. Output_Last + S'Length) := S; Output_Last := Output_Last + S'Length; end Append; procedure Append (S : in Ada.Streams.Stream_Element_Array) is begin Append (To_String (S)); end Append; Verbatim_Code_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Dict.Dict_Last); Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Input_Byte : Ada.Streams.Stream_Element; Verbatim_Length : Ada.Streams.Stream_Element_Offset; begin Output_Last := Output_Buffer'First - 1; while Input_Index in Input'Range loop Input_Byte := Input (Input_Index); if Input_Byte in Dict.Offsets'Range then Append (Dict_Entry (Dict, Input_Byte)); Input_Index := Input_Index + 1; else if not Dict.Variable_Length_Verbatim then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte) + 1; elsif Input_Byte < Ada.Streams.Stream_Element'Last then Verbatim_Length := Ada.Streams.Stream_Element_Offset (Ada.Streams.Stream_Element'Last - Input_Byte); else Input_Index := Input_Index + 1; Verbatim_Length := Ada.Streams.Stream_Element_Offset (Input (Input_Index)) + Verbatim_Code_Count - 1; end if; Append (Input (Input_Index + 1 .. Input_Index + Verbatim_Length)); Input_Index := Input_Index + Verbatim_Length + 1; end if; end loop; end Decompress; function Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return String is Result : String (1 .. Decompressed_Length (Dict, Input)); Last : Natural; begin Decompress (Dict, Input, Result, Last); pragma Assert (Last = Result'Last); return Result; end Decompress; end Natools.Smaz;
fix off-by-one error in Verbatim_Size
smaz: fix off-by-one error in Verbatim_Size
Ada
isc
faelys/natools
4b3ca1b97e52e026cf01ef31b47af902e4872ff0
awa/src/awa-applications.adb
awa/src/awa-applications.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with ASF.Beans; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; with AWA.Components.Factory; with AWA.Applications.Factory; with AWA.Applications.Configs; package body AWA.Applications is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Applications.Configs"); -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class) is URI : constant String := Conf.Get ("database"); begin AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access); App.DB_Factory.Create (URI); ASF.Applications.Main.Application (App).Initialize (Conf, Factory); Application'Class (App).Initialize_Modules; App.Load_Configuration; end Initialize; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Application) is begin ASF.Applications.Main.Application (App).Initialize_Servlets; end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Application) is begin ASF.Applications.Main.Application (App).Initialize_Filters; end Initialize_Filters; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is begin ASF.Applications.Main.Application (App).Initialize_Components; App.Add_Components (AWA.Components.Factory.Definition); end Initialize_Components; -- ------------------------------ -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. -- ------------------------------ overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config) is begin ASF.Applications.Main.Application (App).Initialize_Config (Conf); AWA.Modules.Initialize (App.Modules, Conf); end Initialize_Config; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ procedure Initialize_Modules (App : in out Application) is begin null; end Initialize_Modules; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Load_Configuration (App : in out Application) is Paths : constant String := App.Get_Config (P_Module_Dir.P); Base : constant String := App.Get_Config (P_Config_File.P); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Application configuration file '{0}' does not exist", Path); end Load_Configuration; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin App.Register (Module.all'Unchecked_Access, Name, URI); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.DB_Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.DB_Factory.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access is begin return AWA.Modules.Find_By_Name (App.Modules, Name); end Find_Module; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := "") is -- procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); -- procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory) is -- begin -- Module.Register_Factory (Factory); -- end Set_Beans; -- -- procedure Register_Beans is -- new ASF.Applications.Main.Register_Beans (Set_Beans); begin -- Module.Initialize (); AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); -- Register_Beans (App); -- App.View.Register_Module (Module); SCz: 2011-08-10: must check if necessary end Register; end AWA.Applications;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with ASF.Beans; with ADO.Drivers; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; with AWA.Components.Factory; with AWA.Applications.Factory; with AWA.Applications.Configs; package body AWA.Applications is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Applications.Configs"); -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class) is begin AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access); ASF.Applications.Main.Application (App).Initialize (Conf, Factory); Application'Class (App).Initialize_Modules; App.Load_Configuration; end Initialize; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Application) is begin ASF.Applications.Main.Application (App).Initialize_Servlets; end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Application) is begin ASF.Applications.Main.Application (App).Initialize_Filters; end Initialize_Filters; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is begin ASF.Applications.Main.Application (App).Initialize_Components; App.Add_Components (AWA.Components.Factory.Definition); end Initialize_Components; -- ------------------------------ -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. -- ------------------------------ overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config) is begin ASF.Applications.Main.Application (App).Initialize_Config (Conf); ADO.Drivers.Initialize (Conf); App.DB_Factory.Create (Conf.Get ("database")); AWA.Modules.Initialize (App.Modules, Conf); end Initialize_Config; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ procedure Initialize_Modules (App : in out Application) is begin null; end Initialize_Modules; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Load_Configuration (App : in out Application) is Paths : constant String := App.Get_Config (P_Module_Dir.P); Base : constant String := App.Get_Config (P_Config_File.P); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Application configuration file '{0}' does not exist", Path); end Load_Configuration; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin App.Register (Module.all'Unchecked_Access, Name, URI); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.DB_Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.DB_Factory.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access is begin return AWA.Modules.Find_By_Name (App.Modules, Name); end Find_Module; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := "") is -- procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); -- procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory) is -- begin -- Module.Register_Factory (Factory); -- end Set_Beans; -- -- procedure Register_Beans is -- new ASF.Applications.Main.Register_Beans (Set_Beans); begin -- Module.Initialize (); AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); -- Register_Beans (App); -- App.View.Register_Module (Module); SCz: 2011-08-10: must check if necessary end Register; end AWA.Applications;
Initialize the database connection in Initialize_Config so that the EL expressions in configuration properties gets evaluated
Initialize the database connection in Initialize_Config so that the EL expressions in configuration properties gets evaluated
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
193af992040fd889a1161c20f753a3b5d1401a33
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.ads
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.ads
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with ADO; with AWA.Tests; package AWA.Workspaces.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Member_Id : ADO.Identifier; Key : Ada.Strings.Unbounded.Unbounded_String; end record; -- Verify the anonymous access for the invitation page. procedure Verify_Anonymous (T : in out Test; Key : in String); -- Test sending an invitation. procedure Test_Invite_User (T : in out Test); -- Test deleting the member. procedure Test_Delete_Member (T : in out Test); -- Test accepting the invitation. procedure Test_Accept_Invitation (T : in out Test); -- Test listing the members of the workspace. procedure Test_List_Members (T : in out Test); end AWA.Workspaces.Tests;
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with ADO; with AWA.Tests; package AWA.Workspaces.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Member_Id : ADO.Identifier; Key : Ada.Strings.Unbounded.Unbounded_String; end record; -- Verify the anonymous access for the invitation page. procedure Verify_Anonymous (T : in out Test; Key : in String); -- Test sending an invitation. procedure Test_Invite_User (T : in out Test); -- Test deleting the member. procedure Test_Delete_Member (T : in out Test); -- Test accepting the invitation. procedure Test_Accept_Invitation (T : in out Test); -- Test accepting the invitation with a email and password process. procedure Test_Accept_Invitation_With_Email (T : in out Test); -- Test listing the members of the workspace. procedure Test_List_Members (T : in out Test); end AWA.Workspaces.Tests;
Declare the Test_Accept_Invitation_With_Email procedure
Declare the Test_Accept_Invitation_With_Email procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
30e9949f89d8d40ff1fc90a269e53668d2e9ca7c
awa/plugins/awa-questions/regtests/awa-questions-modules-tests.adb
awa/plugins/awa-questions/regtests/awa-questions-modules-tests.adb
----------------------------------------------------------------------- -- awa-questions-modules-tests -- Unit tests for storage service -- Copyright (C) 2013, 2014, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with ASF.Contexts.Faces; with ASF.Contexts.Faces.Mockup; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Questions.Modules; with AWA.Questions.Beans; with AWA.Votes.Beans; with AWA.Tests.Helpers.Users; package body AWA.Questions.Modules.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Questions.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Services.Delete_Question", Test_Delete_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list", Test_List_Questions'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean", Test_Question_Vote'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)", Test_Question_Vote'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Module; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I append strings in Ada?"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do?"); T.Manager.Save_Question (Q); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do? " & "This is a stupid question for someone who reads this file. " & "But I need some long text for the unit test."); T.Manager.Save_Question (Q); end Test_Create_Question; -- ------------------------------ -- Test deletion of a question. -- ------------------------------ procedure Test_Delete_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Module; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I search strings in Ada?"); Q.Set_Description ("I have two strings that I want to search. % does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); T.Manager.Delete_Question (Q); end Test_Delete_Question; -- ------------------------------ -- Test list of questions. -- ------------------------------ procedure Test_List_Questions (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Module : AWA.Questions.Modules.Question_Module_Access; List : Util.Beans.Basic.Readonly_Bean_Access; Bean : Util.Beans.Objects.Object; Count : Natural; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Module := AWA.Questions.Modules.Get_Question_Module; List := AWA.Questions.Beans.Create_Question_List_Bean (Module); T.Assert (List /= null, "The Create_Question_List_Bean returned null"); Bean := Util.Beans.Objects.To_Object (List); T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null"); T.Assert (List.all in Questions.Beans.Question_List_Bean'Class, "The Create_Question_List_Bean returns an invalid bean"); Count := Questions.Beans.Question_List_Bean'Class (List.all).Questions.Get_Count; T.Assert (Count > 0, "The list of question is empty"); end Test_List_Questions; -- ------------------------------ -- Do a vote on a question through the question vote bean. -- ------------------------------ procedure Do_Vote (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context; Outcome : Ada.Strings.Unbounded.Unbounded_String; Bean : Util.Beans.Basic.Readonly_Bean_Access; Vote : AWA.Votes.Beans.Vote_Bean_Access; begin Context.Set_Parameter ("id", "1"); Bean := Context.Get_Bean ("questionVote"); T.Assert (Bean /= null, "The questionVote bean was not created"); T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class, "The questionVote is not a Vote_Bean"); Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access; Vote.Rating := 1; Vote.Entity_Id := 1; Vote.Vote_Up (Outcome); end Do_Vote; -- ------------------------------ -- Test anonymous user voting for a question. -- ------------------------------ procedure Test_Question_Vote_Anonymous (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Do_Vote (T); T.Fail ("Anonymous users should not be allowed to vote"); exception when AWA.Permissions.NO_PERMISSION => null; end Test_Question_Vote_Anonymous; -- ------------------------------ -- Test voting for a question. -- ------------------------------ procedure Test_Question_Vote (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Do_Vote (T); end Test_Question_Vote; end AWA.Questions.Modules.Tests;
----------------------------------------------------------------------- -- awa-questions-modules-tests -- Unit tests for storage service -- Copyright (C) 2013, 2014, 2018, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with ASF.Contexts.Faces; with ASF.Contexts.Faces.Mockup; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Questions.Beans; with AWA.Votes.Beans; with AWA.Tests.Helpers.Users; package body AWA.Questions.Modules.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Questions.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Services.Delete_Question", Test_Delete_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list", Test_List_Questions'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean", Test_Question_Vote'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)", Test_Question_Vote'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Module; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I append strings in Ada?"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do?"); T.Manager.Save_Question (Q); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do? " & "This is a stupid question for someone who reads this file. " & "But I need some long text for the unit test."); T.Manager.Save_Question (Q); end Test_Create_Question; -- ------------------------------ -- Test deletion of a question. -- ------------------------------ procedure Test_Delete_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Module; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I search strings in Ada?"); Q.Set_Description ("I have two strings that I want to search. % does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); T.Manager.Delete_Question (Q); end Test_Delete_Question; -- ------------------------------ -- Test list of questions. -- ------------------------------ procedure Test_List_Questions (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Module : AWA.Questions.Modules.Question_Module_Access; List : Util.Beans.Basic.Readonly_Bean_Access; Bean : Util.Beans.Objects.Object; Count : Natural; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Module := AWA.Questions.Modules.Get_Question_Module; List := AWA.Questions.Beans.Create_Question_List_Bean (Module); T.Assert (List /= null, "The Create_Question_List_Bean returned null"); Bean := Util.Beans.Objects.To_Object (List); T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null"); T.Assert (List.all in Questions.Beans.Question_List_Bean'Class, "The Create_Question_List_Bean returns an invalid bean"); Count := Questions.Beans.Question_List_Bean'Class (List.all).Questions.Get_Count; T.Assert (Count > 0, "The list of question is empty"); end Test_List_Questions; -- ------------------------------ -- Do a vote on a question through the question vote bean. -- ------------------------------ procedure Do_Vote (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context; Outcome : Ada.Strings.Unbounded.Unbounded_String; Bean : Util.Beans.Basic.Readonly_Bean_Access; Vote : AWA.Votes.Beans.Vote_Bean_Access; begin Context.Set_Parameter ("id", "1"); Bean := Context.Get_Bean ("questionVote"); T.Assert (Bean /= null, "The questionVote bean was not created"); T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class, "The questionVote is not a Vote_Bean"); Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access; Vote.Rating := 1; Vote.Entity_Id := 1; Vote.Vote_Up (Outcome); end Do_Vote; -- ------------------------------ -- Test anonymous user voting for a question. -- ------------------------------ procedure Test_Question_Vote_Anonymous (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Do_Vote (T); T.Fail ("Anonymous users should not be allowed to vote"); exception when AWA.Permissions.NO_PERMISSION => null; end Test_Question_Vote_Anonymous; -- ------------------------------ -- Test voting for a question. -- ------------------------------ procedure Test_Question_Vote (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Do_Vote (T); end Test_Question_Vote; end AWA.Questions.Modules.Tests;
Fix compilation warning with GCC 12: remove unused with clause for an ancestor
Fix compilation warning with GCC 12: remove unused with clause for an ancestor
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
bf6556eb5d67bae81db1ba61240034086b3bc08e
mat/src/mat-consoles-text.adb
mat/src/mat-consoles-text.adb
----------------------------------------------------------------------- -- mat-consoles-text - Text 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. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is begin Ada.Text_IO.Put (Value); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is begin Ada.Text_IO.Put (Title); end Print_Title; end MAT.Consoles.Text;
----------------------------------------------------------------------- -- mat-consoles-text - Text 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. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is begin Ada.Text_IO.Put (Value); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is begin Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
Implement the Start_Row and End_Row operations
Implement the Start_Row and End_Row operations
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f90fd93fb09e7586519ea9988a2aa14756745d03
awa/plugins/awa-questions/src/awa-questions-modules.ads
awa/plugins/awa-questions/src/awa-questions-modules.ads
----------------------------------------------------------------------- -- awa-questions-modules -- Module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with Security.Permissions; with ASF.Applications; with AWA.Modules; with AWA.Questions.Models; package AWA.Questions.Modules is -- The name under which the module is registered. NAME : constant String := "questions"; -- Define the permissions. package ACL_Create_Questions is new Security.Permissions.Definition ("question-create"); package ACL_Delete_Questions is new Security.Permissions.Definition ("question-delete"); package ACL_Update_Questions is new Security.Permissions.Definition ("question-update"); package ACL_Answer_Questions is new Security.Permissions.Definition ("answer-create"); package ACL_Delete_Answer is new Security.Permissions.Definition ("answer-delete"); -- The maximum length for a short description. SHORT_DESCRIPTION_LENGTH : constant Positive := 200; -- ------------------------------ -- Module questions -- ------------------------------ type Question_Module is new AWA.Modules.Module with private; type Question_Module_Access is access all Question_Module'Class; -- Initialize the questions module. overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the questions module. function Get_Question_Module return Question_Module_Access; -- Create or save the question. procedure Save_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class); -- Delete the question. procedure Delete_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class); -- Load the question. procedure Load_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier); -- Create or save the answer. procedure Save_Answer (Model : in Question_Module; Question : in AWA.Questions.Models.Question_Ref'Class; Answer : in out AWA.Questions.Models.Answer_Ref'Class); -- Delete the answer. procedure Delete_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class); -- Load the answer. procedure Load_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier); private type Question_Module is new AWA.Modules.Module with null record; end AWA.Questions.Modules;
----------------------------------------------------------------------- -- awa-questions-modules -- Module questions -- Copyright (C) 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 ADO; with Security.Permissions; with ASF.Applications; with AWA.Modules; with AWA.Questions.Models; package AWA.Questions.Modules is -- The name under which the module is registered. NAME : constant String := "questions"; -- Define the permissions. package ACL_Create_Questions is new Security.Permissions.Definition ("question-create"); package ACL_Delete_Questions is new Security.Permissions.Definition ("question-delete"); package ACL_Update_Questions is new Security.Permissions.Definition ("question-update"); package ACL_Answer_Questions is new Security.Permissions.Definition ("answer-create"); package ACL_Delete_Answer is new Security.Permissions.Definition ("answer-delete"); -- The maximum length for a short description. SHORT_DESCRIPTION_LENGTH : constant Positive := 200; -- ------------------------------ -- Module questions -- ------------------------------ type Question_Module is new AWA.Modules.Module with private; type Question_Module_Access is access all Question_Module'Class; -- Initialize the questions module. overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the questions module. function Get_Question_Module return Question_Module_Access; -- Create or save the question. procedure Save_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class); -- Delete the question. procedure Delete_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class); -- Load the question. procedure Load_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier; Found : out Boolean); -- Create or save the answer. procedure Save_Answer (Model : in Question_Module; Question : in AWA.Questions.Models.Question_Ref'Class; Answer : in out AWA.Questions.Models.Answer_Ref'Class); -- Delete the answer. procedure Delete_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class); -- Load the answer. procedure Load_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier; Found : out Boolean); private type Question_Module is new AWA.Modules.Module with null record; end AWA.Questions.Modules;
Add a Found parameter to the Load_Question and Load_Answer operations
Add a Found parameter to the Load_Question and Load_Answer operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
dd04edabfa329d1bc5e8487d4a0cf981838acefb
awa/src/awa-components-wikis.adb
awa/src/awa-components-wikis.adb
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering 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 Util.Strings; with Util.Beans.Objects; with ASF.Contexts.Writer; with ASF.Utils; with AWA.Wikis.Writers; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return AWA.Wikis.Parsers.Wiki_Syntax_Type is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" then return AWA.Wikis.Parsers.SYNTAX_DOTCLEAR; elsif Format = "google" then return AWA.Wikis.Parsers.SYNTAX_GOOGLE; elsif Format = "phpbb" then return AWA.Wikis.Parsers.SYNTAX_PHPBB; elsif Format = "creole" then return AWA.Wikis.Parsers.SYNTAX_CREOLE; elsif Format = "mediawiki" then return AWA.Wikis.Parsers.SYNTAX_MEDIA_WIKI; else return AWA.Wikis.Parsers.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased AWA.Wikis.Writers.Html_Writer; Format : constant AWA.Wikis.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); begin Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Html.Set_Writer (Writer); AWA.Wikis.Parsers.Parse (Html'Unchecked_Access, Util.Beans.Objects.To_Wide_Wide_String (Value), Format); end if; Writer.End_Element ("div"); end; end Encode_Begin; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- 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.Strings; with Util.Beans.Objects; with ASF.Contexts.Writer; with ASF.Utils; with AWA.Wikis.Writers.Html; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return AWA.Wikis.Parsers.Wiki_Syntax_Type is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" then return AWA.Wikis.Parsers.SYNTAX_DOTCLEAR; elsif Format = "google" then return AWA.Wikis.Parsers.SYNTAX_GOOGLE; elsif Format = "phpbb" then return AWA.Wikis.Parsers.SYNTAX_PHPBB; elsif Format = "creole" then return AWA.Wikis.Parsers.SYNTAX_CREOLE; elsif Format = "mediawiki" then return AWA.Wikis.Parsers.SYNTAX_MEDIA_WIKI; else return AWA.Wikis.Parsers.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased AWA.Wikis.Writers.Html.Html_Writer; Format : constant AWA.Wikis.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); begin Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Html.Set_Writer (Writer); AWA.Wikis.Parsers.Parse (Html'Unchecked_Access, Util.Beans.Objects.To_Wide_Wide_String (Value), Format); end if; Writer.End_Element ("div"); end; end Encode_Begin; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
Use the HTML wiki writer for ASF component
Use the HTML wiki writer for ASF component
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e31e003aa151c082f3bc3f6dd142dd5f63aeecbb
mat/src/mat-commands.adb
mat/src/mat-commands.adb
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Tools; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Frames; with MAT.Frames.Print; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Iter : MAT.Memory.Allocation_Cursor := Target.Memory.Memory_Slots.First; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Type; Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame); Name : Ada.Strings.Unbounded.Unbounded_String; Func : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I))); MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols, Addr => Backtrace (I), Name => Name, Func => Func, Line => Line); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name)); if Line /= 0 then Ada.Text_IO.Put (":"); Ada.Text_IO.Put (Util.Strings.Image (Line)); end if; Ada.Text_IO.New_Line; end loop; end Print; begin while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Iter : MAT.Memory.Tools.Size_Info_Cursor; begin MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Size)); Ada.Text_IO.Set_Col (20); Ada.Text_IO.Put (Natural'Image (Info.Count)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put_Line (MAT.Types.Target_Size'Image (Total)); end; MAT.Memory.Tools.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); elsif Command'Length > 0 then Ada.Text_IO.Put_Line ("Command '" & Command & "' not found"); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); end MAT.Commands;
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Tools; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Frames; with MAT.Frames.Print; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Slots : MAT.Memory.Allocation_Map; Iter : MAT.Memory.Allocation_Cursor; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Type; Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame); Name : Ada.Strings.Unbounded.Unbounded_String; Func : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I))); MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols, Addr => Backtrace (I), Name => Name, Func => Func, Line => Line); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name)); if Line /= 0 then Ada.Text_IO.Put (":"); Ada.Text_IO.Put (Util.Strings.Image (Line)); end if; Ada.Text_IO.New_Line; end loop; end Print; begin Target.Memory.Find (From => MAT.Types.Target_Addr'First, To => MAT.Types.Target_Addr'Last, Into => Slots); Iter := Slots.First; while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Iter : MAT.Memory.Tools.Size_Info_Cursor; begin MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Size)); Ada.Text_IO.Set_Col (20); Ada.Text_IO.Put (Natural'Image (Info.Count)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put_Line (MAT.Types.Target_Size'Image (Total)); end; MAT.Memory.Tools.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); elsif Command'Length > 0 then Ada.Text_IO.Put_Line ("Command '" & Command & "' not found"); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); end MAT.Commands;
Use the Find procedure to collect the memory slots
Use the Find procedure to collect the memory slots
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1f9506f6ceb481a671fc908ba09192d1682245d5
mat/src/mat-consoles.adb
mat/src/mat-consoles.adb
----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- package body MAT.Consoles is -- ------------------------------ -- 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) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- 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) is Value : constant String := MAT.Types.Hex_Image (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the address range and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) is From_Value : constant String := MAT.Types.Hex_Image (From); To_Value : constant String := MAT.Types.Hex_Image (To); begin Console_Type'Class (Console).Print_Field (Field, From_Value & "-" & To_Value); end Print_Field; -- ------------------------------ -- 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) is Value : constant String := MAT.Types.Target_Size'Image (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Types.Tick_Image (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT) is Val : constant String := Integer'Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val, Justify); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT) is Item : String := Ada.Strings.Unbounded.To_String (Value); Size : constant Natural := Console.Sizes (Field); begin if Size <= Item'Length then Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "..."; Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last)); else Console_Type'Class (Console).Print_Field (Field, Item, Justify); end if; end Print_Field; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with MAT.Formats; package body MAT.Consoles is -- ------------------------------ -- 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) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- 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) is Value : constant String := MAT.Formats.Addr (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the address range and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) is From_Value : constant String := MAT.Formats.Addr (From); To_Value : constant String := MAT.Formats.Addr (To); begin Console_Type'Class (Console).Print_Field (Field, From_Value & "-" & To_Value); end Print_Field; -- ------------------------------ -- 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) is Value : constant String := MAT.Types.Target_Size'Image (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Formats.Duration (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT) is Val : constant String := Util.Strings.Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val, Justify); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT) is Item : String := Ada.Strings.Unbounded.To_String (Value); Size : constant Natural := Console.Sizes (Field); begin if Size <= Item'Length then Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "..."; Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last)); else Console_Type'Class (Console).Print_Field (Field, Item, Justify); end if; end Print_Field; end MAT.Consoles;
Use the MAT.Formats.Addr function to format an address
Use the MAT.Formats.Addr function to format an address
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
26ee6b1dd70478aa201c5a31437fa509c3607453
awa/plugins/awa-wikis/regtests/awa-wikis-tests.ads
awa/plugins/awa-wikis/regtests/awa-wikis-tests.ads
----------------------------------------------------------------------- -- 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.Tests; with AWA.Tests; with Ada.Strings.Unbounded; package AWA.Wikis.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Wiki_Ident : Ada.Strings.Unbounded.Unbounded_String; Page_Ident : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the wiki page as anonymous users. procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String); -- Verify that the wiki lists contain the given page. procedure Verify_List_Contains (T : in out Test; Page : in String); -- Test access to the wiki as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of wiki space and page by simulating web requests. procedure Test_Create_Wiki (T : in out Test); -- Test getting a wiki page which does not exist. procedure Test_Missing_Page (T : in out Test); end AWA.Wikis.Tests;
----------------------------------------------------------------------- -- awa-wikis-tests -- Unit tests for wikis module -- Copyright (C) 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; with Servlet.requests.Mockup; with Servlet.Responses.Mockup; with Ada.Strings.Unbounded; package AWA.Wikis.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Wiki_Ident : Ada.Strings.Unbounded.Unbounded_String; Page_Ident : Ada.Strings.Unbounded.Unbounded_String; Image_Ident : Ada.Strings.Unbounded.Unbounded_String; end record; -- Setup an image for the wiki page. procedure Make_Wiki_Image (T : in out Test); -- Create a wiki page. procedure Create_Page (T : in out Test; Request : in out Servlet.Requests.Mockup.Request; Reply : in out Servlet.Responses.Mockup.Response; Name : in String; Title : in String); -- Get some access on the wiki page as anonymous users. procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String); -- Verify that the wiki lists contain the given page. procedure Verify_List_Contains (T : in out Test; Page : in String); -- Test access to the wiki as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of wiki space and page by simulating web requests. procedure Test_Create_Wiki (T : in out Test); -- Test getting a wiki page which does not exist. procedure Test_Missing_Page (T : in out Test); -- Test creation of wiki page with an image. procedure Test_Page_With_Image (T : in out Test); end AWA.Wikis.Tests;
Add Test_Page_With_Image unit test
Add Test_Page_With_Image unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
82665b9ea4f5c39670df8ab68e3ee637f28ff4ee
regtests/wiki-parsers-tests.adb
regtests/wiki-parsers-tests.adb
----------------------------------------------------------------------- -- wiki-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Wiki.Utils; with Wiki.Writers; package body Wiki.Parsers.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Parsers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (bold)", Test_Wiki_Bold'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic)", Test_Wiki_Italic'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic, bold)", Test_Wiki_Formats'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (headings)", Test_Wiki_Section'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (lists)", Test_Wiki_List'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (links)", Test_Wiki_Link'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (quote)", Test_Wiki_Quote'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (line break)", Test_Wiki_Line_Break'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (image)", Test_Wiki_Image'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (preformatted)", Test_Wiki_Preformatted'Access); Caller.Add_Test (Suite, "Test Wiki.Text.Renderer", Test_Wiki_Text_Renderer'Access); end Add_Tests; -- ------------------------------ -- Test bold rendering. -- ------------------------------ procedure Test_Wiki_Bold (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>", Wiki.Utils.To_Html ("*bold*", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x *bold* y", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>", Wiki.Utils.To_Html ("x *bold y", SYNTAX_MIX), "Bold rendering invalid (MIX)"); Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>", Wiki.Utils.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>", Wiki.Utils.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR), "No bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x '''bold''' y", SYNTAX_PHPBB), "Bold rendering invalid (PHPBB)"); end Test_Wiki_Bold; -- ------------------------------ -- Test italic rendering. -- ------------------------------ procedure Test_Wiki_Italic (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>item</i></p>", Wiki.Utils.To_Html ("_item_", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_MIX), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>", Wiki.Utils.To_Html ("x 'item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); end Test_Wiki_Italic; -- ------------------------------ -- Test various format rendering. -- ------------------------------ procedure Test_Wiki_Formats (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>", Wiki.Utils.To_Html ("_it*bold*em_", SYNTAX_GOOGLE), "Italic+Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_GOOGLE), "Italic rendering invalid"); end Test_Wiki_Formats; -- ------------------------------ -- Test heading rendering. -- ------------------------------ procedure Test_Wiki_Section (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<h1>item</h1>", Wiki.Utils.To_Html ("= item =", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h2>item</h2>", Wiki.Utils.To_Html ("== item == ", SYNTAX_GOOGLE), "H2 rendering invalid"); Util.Tests.Assert_Equals (T, "<h3>item</h3>", Wiki.Utils.To_Html ("=== item === ", SYNTAX_GOOGLE), "H3 rendering invalid"); Util.Tests.Assert_Equals (T, "<h4>item</h4>", Wiki.Utils.To_Html ("==== item ==== ", SYNTAX_GOOGLE), "H4 rendering invalid"); Util.Tests.Assert_Equals (T, "<h5>item</h5>", Wiki.Utils.To_Html ("===== item =====", SYNTAX_GOOGLE), "H5 rendering invalid"); Util.Tests.Assert_Equals (T, "<h6>item</h6>", Wiki.Utils.To_Html ("====== item ===", SYNTAX_GOOGLE), "H6 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =", SYNTAX_GOOGLE), "H1 rendering invalid"); end Test_Wiki_Section; -- ------------------------------ -- Test list rendering. -- ------------------------------ procedure Test_Wiki_List (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>", Wiki.Utils.To_Html ("# item", SYNTAX_GOOGLE), "Ordered list rendering invalid"); Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF & "</li><li>item2 item2" & ASCII.LF & "</li><li><ol>item3</li></ol></ol>", Wiki.Utils.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3", SYNTAX_GOOGLE), "Ordered rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html (" * item", SYNTAX_GOOGLE), "Bullet list rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html ("* item", SYNTAX_DOTCLEAR), "Bullet list rendering invalid"); end Test_Wiki_List; -- ------------------------------ -- Test link rendering. -- ------------------------------ procedure Test_Wiki_Link (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>", Wiki.Utils.To_Html ("[name]", SYNTAX_GOOGLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a title=""some"" lang=""en"" " & "href=""http://www.joe.com/item"">name </a></p>", Wiki.Utils.To_Html ("[name |http://www.joe.com/item|en|some]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_CREOLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p>[d</p>", Wiki.Utils.To_Html ("[d", SYNTAX_CREOLE), "No link rendering invalid"); end Test_Wiki_Link; -- ------------------------------ -- Test quote rendering. -- ------------------------------ procedure Test_Wiki_Quote (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>", Wiki.Utils.To_Html ("{{quote}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"" cite=""http://www.sun.com"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en|http://www.sun.com}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p>{quote}}</p>", Wiki.Utils.To_Html ("{quote}}", SYNTAX_DOTCLEAR), "No quote rendering invalid"); end Test_Wiki_Quote; -- ------------------------------ -- Test line break rendering. -- ------------------------------ procedure Test_Wiki_Line_Break (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a%%%b", SYNTAX_DOTCLEAR), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a\\b", SYNTAX_CREOLE), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%%b</p>", Wiki.Utils.To_Html ("a%%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%b</p>", Wiki.Utils.To_Html ("a%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); end Test_Wiki_Line_Break; -- ------------------------------ -- Test image rendering. -- ------------------------------ procedure Test_Wiki_Image (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png""></img></p>", Wiki.Utils.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png""></img></p>", Wiki.Utils.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" longdesc=""describe"" " & "src=""/image/t.png""></img></p>", Wiki.Utils.To_Html ("((/image/t.png|title|D|describe))", SYNTAX_DOTCLEAR), "Image rendering invalid"); end Test_Wiki_Image; -- ------------------------------ -- Test preformatted rendering. -- ------------------------------ procedure Test_Wiki_Preformatted (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>", Wiki.Utils.To_Html ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>", Wiki.Utils.To_Html ("///" & LF & "* code *" & LF & "///", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); end Test_Wiki_Preformatted; -- ------------------------------ -- Test the text renderer. -- ------------------------------ procedure Test_Wiki_Text_Renderer (T : in out Test) is begin Util.Tests.Assert_Equals (T, ASCII.LF & "code", Wiki.Utils.To_Text ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF, Wiki.Utils.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE), "Preformat rendering invalid"); end Test_Wiki_Text_Renderer; end Wiki.Parsers.Tests;
----------------------------------------------------------------------- -- wiki-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Wiki.Utils; package body Wiki.Parsers.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Parsers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (bold)", Test_Wiki_Bold'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic)", Test_Wiki_Italic'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic, bold)", Test_Wiki_Formats'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (headings)", Test_Wiki_Section'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (lists)", Test_Wiki_List'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (links)", Test_Wiki_Link'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (quote)", Test_Wiki_Quote'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (line break)", Test_Wiki_Line_Break'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (image)", Test_Wiki_Image'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (preformatted)", Test_Wiki_Preformatted'Access); Caller.Add_Test (Suite, "Test Wiki.Text.Renderer", Test_Wiki_Text_Renderer'Access); end Add_Tests; -- ------------------------------ -- Test bold rendering. -- ------------------------------ procedure Test_Wiki_Bold (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>", Wiki.Utils.To_Html ("*bold*", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x *bold* y", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>", Wiki.Utils.To_Html ("x *bold y", SYNTAX_MIX), "Bold rendering invalid (MIX)"); Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>", Wiki.Utils.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>", Wiki.Utils.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR), "No bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x '''bold''' y", SYNTAX_PHPBB), "Bold rendering invalid (PHPBB)"); end Test_Wiki_Bold; -- ------------------------------ -- Test italic rendering. -- ------------------------------ procedure Test_Wiki_Italic (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>item</i></p>", Wiki.Utils.To_Html ("_item_", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_MIX), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>", Wiki.Utils.To_Html ("x 'item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); end Test_Wiki_Italic; -- ------------------------------ -- Test various format rendering. -- ------------------------------ procedure Test_Wiki_Formats (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>", Wiki.Utils.To_Html ("_it*bold*em_", SYNTAX_GOOGLE), "Italic+Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_GOOGLE), "Italic rendering invalid"); end Test_Wiki_Formats; -- ------------------------------ -- Test heading rendering. -- ------------------------------ procedure Test_Wiki_Section (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<h1>item</h1>", Wiki.Utils.To_Html ("= item =", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h2>item</h2>", Wiki.Utils.To_Html ("== item == ", SYNTAX_GOOGLE), "H2 rendering invalid"); Util.Tests.Assert_Equals (T, "<h3>item</h3>", Wiki.Utils.To_Html ("=== item === ", SYNTAX_GOOGLE), "H3 rendering invalid"); Util.Tests.Assert_Equals (T, "<h4>item</h4>", Wiki.Utils.To_Html ("==== item ==== ", SYNTAX_GOOGLE), "H4 rendering invalid"); Util.Tests.Assert_Equals (T, "<h5>item</h5>", Wiki.Utils.To_Html ("===== item =====", SYNTAX_GOOGLE), "H5 rendering invalid"); Util.Tests.Assert_Equals (T, "<h6>item</h6>", Wiki.Utils.To_Html ("====== item ===", SYNTAX_GOOGLE), "H6 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =", SYNTAX_GOOGLE), "H1 rendering invalid"); end Test_Wiki_Section; -- ------------------------------ -- Test list rendering. -- ------------------------------ procedure Test_Wiki_List (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>", Wiki.Utils.To_Html ("# item", SYNTAX_GOOGLE), "Ordered list rendering invalid"); Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF & "</li><li>item2 item2" & ASCII.LF & "</li><li><ol>item3</li></ol></ol>", Wiki.Utils.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3", SYNTAX_GOOGLE), "Ordered rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html (" * item", SYNTAX_GOOGLE), "Bullet list rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html ("* item", SYNTAX_DOTCLEAR), "Bullet list rendering invalid"); end Test_Wiki_List; -- ------------------------------ -- Test link rendering. -- ------------------------------ procedure Test_Wiki_Link (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[name]", SYNTAX_GOOGLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a title=""some"" lang=""en"" " & "href=""http://www.joe.com/item"">name </a></p>", Wiki.Utils.To_Html ("[name |http://www.joe.com/item|en|some]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_CREOLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p>[d</p>", Wiki.Utils.To_Html ("[d", SYNTAX_CREOLE), "No link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a " & "href=""http://www.joe.com/item"">http://www.joe.com/item</a></p>", Wiki.Utils.To_Html ("[http://www.joe.com/item]", SYNTAX_DOTCLEAR), "Link rendering invalid"); end Test_Wiki_Link; -- ------------------------------ -- Test quote rendering. -- ------------------------------ procedure Test_Wiki_Quote (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>", Wiki.Utils.To_Html ("{{quote}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"" cite=""http://www.sun.com"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en|http://www.sun.com}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p>{quote}}</p>", Wiki.Utils.To_Html ("{quote}}", SYNTAX_DOTCLEAR), "No quote rendering invalid"); end Test_Wiki_Quote; -- ------------------------------ -- Test line break rendering. -- ------------------------------ procedure Test_Wiki_Line_Break (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a%%%b", SYNTAX_DOTCLEAR), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a\\b", SYNTAX_CREOLE), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%%b</p>", Wiki.Utils.To_Html ("a%%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%b</p>", Wiki.Utils.To_Html ("a%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); end Test_Wiki_Line_Break; -- ------------------------------ -- Test image rendering. -- ------------------------------ procedure Test_Wiki_Image (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png""></img></p>", Wiki.Utils.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png""></img></p>", Wiki.Utils.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" longdesc=""describe"" " & "src=""/image/t.png""></img></p>", Wiki.Utils.To_Html ("((/image/t.png|title|D|describe))", SYNTAX_DOTCLEAR), "Image rendering invalid"); end Test_Wiki_Image; -- ------------------------------ -- Test preformatted rendering. -- ------------------------------ procedure Test_Wiki_Preformatted (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>", Wiki.Utils.To_Html ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>", Wiki.Utils.To_Html ("///" & LF & "* code *" & LF & "///", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); end Test_Wiki_Preformatted; -- ------------------------------ -- Test the text renderer. -- ------------------------------ procedure Test_Wiki_Text_Renderer (T : in out Test) is begin Util.Tests.Assert_Equals (T, ASCII.LF & "code", Wiki.Utils.To_Text ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF, Wiki.Utils.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE), "Preformat rendering invalid"); end Test_Wiki_Text_Renderer; end Wiki.Parsers.Tests;
Update the test to take into account the correct link generation
Update the test to take into account the correct link generation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
43b4c0fffaebc144afa5f3766be67f66c5c35851
opengl-vertex.ads
opengl-vertex.ads
with OpenGL.Thin; package OpenGL.Vertex is type Primitive_Type_t is (Points, Line_Strip, Line_Loop, Lines, Triangle_Strip, Triangle_Fan, Triangles, Quad_Strip, Quads, Polygon); -- -- Immediate mode. Begin/End. -- -- proc_map : glBegin procedure GL_Begin (Mode : in Primitive_Type_t); -- proc_map : glEnd procedure GL_End renames Thin.GL_End; -- -- Map primitive types to enumerations. -- function Primitive_Type_To_Constant (Mode : in Primitive_Type_t) return Thin.Enumeration_t; end OpenGL.Vertex;
with OpenGL.Thin; with OpenGL.Types; package OpenGL.Vertex is type Primitive_Type_t is (Points, Line_Strip, Line_Loop, Lines, Triangle_Strip, Triangle_Fan, Triangles, Quad_Strip, Quads, Polygon); -- -- Immediate mode. Begin/End. -- -- proc_map : glBegin procedure GL_Begin (Mode : in Primitive_Type_t); -- proc_map : glEnd procedure GL_End renames Thin.GL_End; -- proc_map : glVertex4f procedure Vertex_4f (X : in Types.Float_t; Y : in Types.Float_t; Z : in Types.Float_t; W : in Types.Float_t) renames Thin.Vertex_4f; -- proc_map : glVertex3f procedure Vertex_3f (X : in Types.Float_t; Y : in Types.Float_t; Z : in Types.Float_t) renames Thin.Vertex_3f; -- proc_map : glVertex2f procedure Vertex_2f (X : in Types.Float_t; Y : in Types.Float_t) renames Thin.Vertex_2f; -- proc_map : glVertex4d procedure Vertex_4d (X : in Types.Double_t; Y : in Types.Double_t; Z : in Types.Double_t; W : in Types.Double_t) renames Thin.Vertex_4d; -- proc_map : glVertex3d procedure Vertex_3d (X : in Types.Double_t; Y : in Types.Double_t; Z : in Types.Double_t) renames Thin.Vertex_3d; -- proc_map : glVertex2d procedure Vertex_2d (X : in Types.Double_t; Y : in Types.Double_t) renames Thin.Vertex_2d; -- proc_map : glVertex4i procedure Vertex_4i (X : in Types.Integer_t; Y : in Types.Integer_t; Z : in Types.Integer_t; W : in Types.Integer_t) renames Thin.Vertex_4i; -- proc_map : glVertex3i procedure Vertex_3i (X : in Types.Integer_t; Y : in Types.Integer_t; Z : in Types.Integer_t) renames Thin.Vertex_3i; -- proc_map : glVertex2i procedure Vertex_2i (X : in Types.Integer_t; Y : in Types.Integer_t) renames Thin.Vertex_2i; -- -- Map primitive types to enumerations. -- function Primitive_Type_To_Constant (Mode : in Primitive_Type_t) return Thin.Enumeration_t; end OpenGL.Vertex;
Add Vertex_*
Add Vertex_*
Ada
isc
io7m/coreland-opengl-ada,io7m/coreland-opengl-ada
e79fa0fd433f783819371e4becc9487cf16c829d
awa/samples/src/atlas-microblog-modules.adb
awa/samples/src/atlas-microblog-modules.adb
----------------------------------------------------------------------- -- atlas-microblog-modules -- Module microblog -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Services.Contexts; with ADO.Sessions; with Util.Log.Loggers; with Atlas.Microblog.Beans; package body Atlas.Microblog.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Microblog.Module"); package Register is new AWA.Modules.Beans (Module => Microblog_Module, Module_Access => Microblog_Module_Access); -- ------------------------------ -- Initialize the microblog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Microblog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the microblog module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "Atlas.Microblog.Beans.Microblog_Bean", Handler => Atlas.Microblog.Beans.Create_Microblog_Bean'Access); Register.Register (Plugin => Plugin, Name => "Atlas.Microblog.Beans.List_Bean", Handler => Atlas.Microblog.Beans.Create_List_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the microblog module. -- ------------------------------ function Get_Microblog_Module return Microblog_Module_Access is function Get is new AWA.Modules.Get (Microblog_Module, Microblog_Module_Access, NAME); begin return Get; end Get_Microblog_Module; -- ------------------------------ -- Create a post for the microblog. -- ------------------------------ procedure Create (Plugin : in Microblog_Module; Post : in out Atlas.Microblog.Models.Mblog_Ref) is pragma Unreferenced (Plugin); use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Author (Ctx.Get_User); Post.Save (DB); Ctx.Commit; end Create; end Atlas.Microblog.Modules;
----------------------------------------------------------------------- -- atlas-microblog-modules -- Module microblog -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Services.Contexts; with ADO.Sessions; with Util.Log.Loggers; with Atlas.Microblog.Beans; package body Atlas.Microblog.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Microblog.Module"); package Register is new AWA.Modules.Beans (Module => Microblog_Module, Module_Access => Microblog_Module_Access); -- ------------------------------ -- Initialize the microblog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Microblog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the microblog module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "Atlas.Microblog.Beans.Microblog_Bean", Handler => Atlas.Microblog.Beans.Create_Microblog_Bean'Access); Register.Register (Plugin => Plugin, Name => "Atlas.Microblog.Beans.List_Bean", Handler => Atlas.Microblog.Beans.Create_List_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the microblog module. -- ------------------------------ function Get_Microblog_Module return Microblog_Module_Access is function Get is new AWA.Modules.Get (Microblog_Module, Microblog_Module_Access, NAME); begin return Get; end Get_Microblog_Module; -- ------------------------------ -- Create a post for the microblog. -- ------------------------------ procedure Create (Plugin : in Microblog_Module; Post : in out Atlas.Microblog.Models.Mblog_Ref) is pragma Unreferenced (Plugin); use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; Post.Set_Creation_Date (Ada.Calendar.Clock); Post.Set_Author (Ctx.Get_User); Post.Save (DB); Ctx.Commit; end Create; end Atlas.Microblog.Modules;
Rename Set_Create_Date into Set_Creation_Date
Rename Set_Create_Date into Set_Creation_Date
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1ed6df70a4de4a735c13883e31bb4d6ab78f1e52
regtests/wiki-writers-tests.ads
regtests/wiki-writers-tests.ads
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; with Wiki.Parsers; package Wiki.Writers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test_Case with record Writer : Integer; Name : Ada.Strings.Unbounded.Unbounded_String; File : Ada.Strings.Unbounded.Unbounded_String; Expect : Ada.Strings.Unbounded.Unbounded_String; Result : Ada.Strings.Unbounded.Unbounded_String; Format : Wiki.Parsers.Wiki_Syntax_Type; Is_Html : Boolean := False; end record; type Test_Case_Access is access all Test; -- Test case name overriding function Name (T : Test) return Util.Tests.Message_String; -- Perform the test. overriding procedure Run_Test (T : in out Test); -- Test rendering a wiki text in HTML or text. procedure Test_Render (T : in out Test); end Wiki.Writers.Tests;
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 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 Util.Tests; with Ada.Strings.Unbounded; with Wiki.Parsers; package Wiki.Writers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test_Case with record Writer : Integer; Name : Ada.Strings.Unbounded.Unbounded_String; File : Ada.Strings.Unbounded.Unbounded_String; Expect : Ada.Strings.Unbounded.Unbounded_String; Result : Ada.Strings.Unbounded.Unbounded_String; Source : Wiki.Parsers.Wiki_Syntax_Type; Format : Wiki.Parsers.Wiki_Syntax_Type; Is_Html : Boolean := False; end record; type Test_Case_Access is access all Test; -- Test case name overriding function Name (T : Test) return Util.Tests.Message_String; -- Perform the test. overriding procedure Run_Test (T : in out Test); -- Test rendering a wiki text in HTML or text. procedure Test_Render (T : in out Test); end Wiki.Writers.Tests;
Add a Source syntax format
Add a Source syntax format
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
ac026740aa07f06153bf8aae09b3f2b6dd950d31
matp/src/mat-expressions.ads
matp/src/mat-expressions.ads
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; with MAT.Events.Targets; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_DIRECT_FILE, INSIDE_FUNCTION, INSIDE_DIRECT_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Create an event ID range expression node. function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type; -- Create a thread ID range expression node. function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type; -- Create a event type expression check. function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean; -- Parse the string and return the expression tree. function Parse (Expr : in String) return Expression_Type; -- Empty expression. EMPTY : constant Expression_Type; type yystype is record low : MAT.Types.Uint64 := 0; high : MAT.Types.Uint64 := 0; bval : Boolean := False; name : Ada.Strings.Unbounded.Unbounded_String; expr : Expression_Type; end record; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_EVENT, N_HAS_ADDR, N_CONDITION, N_THREAD, N_TYPE); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT | N_HAS_ADDR => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Min_Thread : MAT.Types.Target_Thread_Ref; Max_Thread : MAT.Types.Target_Thread_Ref; when N_EVENT => Min_Event : MAT.Events.Targets.Event_Id_Type; Max_Event : MAT.Events.Targets.Event_Id_Type; when N_TYPE => Event_Kind : MAT.Events.Targets.Probe_Index_Type; when others => null; end case; end record; -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean; type Expression_Type is new Ada.Finalization.Controlled with record Node : Node_Type_Access; end record; -- Release the reference and destroy the expression tree if it was the last reference. overriding procedure Finalize (Obj : in out Expression_Type); -- Update the reference after an assignment. overriding procedure Adjust (Obj : in out Expression_Type); -- Empty expression. EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with Node => null); end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; with MAT.Events.Targets; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_DIRECT_FILE, INSIDE_FUNCTION, INSIDE_DIRECT_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Create an event ID range expression node. function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type; -- Create a thread ID range expression node. function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type; -- Create a event type expression check. function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean; -- Parse the string and return the expression tree. function Parse (Expr : in String) return Expression_Type; -- Empty expression. EMPTY : constant Expression_Type; type yystype is record low : MAT.Types.Uint64 := 0; high : MAT.Types.Uint64 := 0; bval : Boolean := False; name : Ada.Strings.Unbounded.Unbounded_String; expr : Expression_Type; end record; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_EVENT, N_HAS_ADDR, N_CONDITION, N_THREAD, N_TYPE, N_NO_FREE); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT | N_HAS_ADDR => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Min_Thread : MAT.Types.Target_Thread_Ref; Max_Thread : MAT.Types.Target_Thread_Ref; when N_EVENT => Min_Event : MAT.Events.Targets.Event_Id_Type; Max_Event : MAT.Events.Targets.Event_Id_Type; when N_TYPE => Event_Kind : MAT.Events.Targets.Probe_Index_Type; when others => null; end case; end record; -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean; type Expression_Type is new Ada.Finalization.Controlled with record Node : Node_Type_Access; end record; -- Release the reference and destroy the expression tree if it was the last reference. overriding procedure Finalize (Obj : in out Expression_Type); -- Update the reference after an assignment. overriding procedure Adjust (Obj : in out Expression_Type); -- Empty expression. EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with Node => null); end MAT.Expressions;
Add N_NO_FREE in the Kind_Type enum
Add N_NO_FREE in the Kind_Type enum
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
201041070cc22501a592aecb6e0ee6665cd34efa
regtests/asf-converters-tests.adb
regtests/asf-converters-tests.adb
----------------------------------------------------------------------- -- Faces Context Tests - Unit tests for ASF.Contexts.Faces -- 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 Ada.Calendar; with Ada.Calendar.Formatting; with Ada.Unchecked_Deallocation; with Util.Beans.Objects.Time; with Util.Test_Caller; with ASF.Tests; with ASF.Components.Html.Text; with ASF.Converters.Dates; package body ASF.Converters.Tests is use Util.Tests; use ASF.Converters.Dates; package Caller is new Util.Test_Caller (Test, "Converters"); procedure Test_Date_Conversion (T : in out Test; Date_Style : in Dates.Style_Type; Time_Style : in Dates.Style_Type; Expect : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Short)", Test_Date_Short_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Medium)", Test_Date_Medium_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Long)", Test_Date_Long_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Full)", Test_Date_Full_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Short)", Test_Time_Short_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Medium)", Test_Time_Medium_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Long)", Test_Time_Long_Converter'Access); end Add_Tests; -- ------------------------------ -- Test getting an attribute from the faces context. -- ------------------------------ procedure Test_Date_Conversion (T : in out Test; Date_Style : in Dates.Style_Type; Time_Style : in Dates.Style_Type; Expect : in String) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Dates.Date_Converter'Class, Name => ASF.Converters.Dates.Date_Converter_Access); Ctx : aliased ASF.Contexts.Faces.Faces_Context; UI : ASF.Components.Html.Text.UIOutput; C : ASF.Converters.Dates.Date_Converter_Access; D : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 3, 4, 5); begin T.Setup (Ctx); ASF.Contexts.Faces.Set_Current (Ctx'Unchecked_Access, ASF.Tests.Get_Application.all'Access); if Date_Style = Dates.DEFAULT then C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.TIME, Locale => "en", Pattern => ""); elsif Time_Style = Dates.DEFAULT then C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.DATE, Locale => "en", Pattern => ""); else C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.BOTH, Locale => "en", Pattern => ""); end if; UI.Set_Converter (C.all'Access); declare R : constant String := C.To_String (Ctx, UI, Util.Beans.Objects.Time.To_Object (D)); begin Util.Tests.Assert_Equals (T, Expect, R, "Invalid date conversion"); end; Free (C); end Test_Date_Conversion; -- ------------------------------ -- Test the date short converter. -- ------------------------------ procedure Test_Date_Short_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.SHORT, ASF.Converters.Dates.DEFAULT, "19/11/2011"); end Test_Date_Short_Converter; -- ------------------------------ -- Test the date medium converter. -- ------------------------------ procedure Test_Date_Medium_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.MEDIUM, ASF.Converters.Dates.DEFAULT, "Nov 19, 2011"); end Test_Date_Medium_Converter; -- ------------------------------ -- Test the date long converter. -- ------------------------------ procedure Test_Date_Long_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.LONG, ASF.Converters.Dates.DEFAULT, "November 19, 2011"); end Test_Date_Long_Converter; -- ------------------------------ -- Test the date full converter. -- ------------------------------ procedure Test_Date_Full_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.FULL, ASF.Converters.Dates.DEFAULT, "Saturday, November 19, 2011"); end Test_Date_Full_Converter; -- ------------------------------ -- Test the time short converter. -- ------------------------------ procedure Test_Time_Short_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.SHORT, "03:04"); end Test_Time_Short_Converter; -- ------------------------------ -- Test the time short converter. -- ------------------------------ procedure Test_Time_Medium_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.MEDIUM, "03:04"); end Test_Time_Medium_Converter; -- ------------------------------ -- Test the time long converter. -- ------------------------------ procedure Test_Time_Long_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.LONG, "03:04:05"); end Test_Time_Long_Converter; end ASF.Converters.Tests;
----------------------------------------------------------------------- -- Faces Context Tests - Unit tests for ASF.Contexts.Faces -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Calendar.Formatting; with Ada.Unchecked_Deallocation; with Util.Beans.Objects.Time; with Util.Test_Caller; with Util.Dates; with ASF.Tests; with ASF.Components.Html.Text; with ASF.Converters.Dates; package body ASF.Converters.Tests is use Util.Tests; use ASF.Converters.Dates; package Caller is new Util.Test_Caller (Test, "Converters"); procedure Test_Date_Conversion (T : in out Test; Date_Style : in Dates.Style_Type; Time_Style : in Dates.Style_Type; Expect : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Short)", Test_Date_Short_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Medium)", Test_Date_Medium_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Long)", Test_Date_Long_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Full)", Test_Date_Full_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Short)", Test_Time_Short_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Medium)", Test_Time_Medium_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Long)", Test_Time_Long_Converter'Access); end Add_Tests; -- ------------------------------ -- Test getting an attribute from the faces context. -- ------------------------------ procedure Test_Date_Conversion (T : in out Test; Date_Style : in Dates.Style_Type; Time_Style : in Dates.Style_Type; Expect : in String) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Dates.Date_Converter'Class, Name => ASF.Converters.Dates.Date_Converter_Access); Ctx : aliased ASF.Contexts.Faces.Faces_Context; UI : ASF.Components.Html.Text.UIOutput; C : ASF.Converters.Dates.Date_Converter_Access; D : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 3, 4, 5); begin T.Setup (Ctx); ASF.Contexts.Faces.Set_Current (Ctx'Unchecked_Access, ASF.Tests.Get_Application.all'Access); if Date_Style = Dates.DEFAULT then C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.TIME, Locale => "en", Pattern => ""); elsif Time_Style = Dates.DEFAULT then C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.DATE, Locale => "en", Pattern => ""); else C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.BOTH, Locale => "en", Pattern => ""); end if; UI.Set_Converter (C.all'Access); declare use type Ada.Calendar.Time; R : constant String := C.To_String (Ctx, UI, Util.Beans.Objects.Time.To_Object (D)); V : Util.Beans.Objects.Object; S : Util.Dates.Date_Record; begin Util.Tests.Assert_Equals (T, Expect, R, "Invalid date conversion"); V := C.To_Object (Ctx, UI, R); Util.Dates.Split (Into => S, Date => Util.Beans.Objects.Time.To_Time (V)); if Date_Style /= Dates.DEFAULT then T.Assert (Util.Dates.Is_Same_Day (Util.Beans.Objects.Time.To_Time (V), D), "Invalid date"); else Util.Tests.Assert_Equals (T, 3, Natural (S.Hour), "Invalid date conversion: hour"); Util.Tests.Assert_Equals (T, 4, Natural (S.Minute), "Invalid date conversion: minute"); if Time_Style = Dates.LONG then Util.Tests.Assert_Equals (T, 5, Natural (S.Second), "Invalid date conversion: second"); end if; end if; exception when E : others => -- T.Fail ("Exception when converting date string: " & R); raise; end; Free (C); end Test_Date_Conversion; -- ------------------------------ -- Test the date short converter. -- ------------------------------ procedure Test_Date_Short_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.SHORT, ASF.Converters.Dates.DEFAULT, "19/11/2011"); end Test_Date_Short_Converter; -- ------------------------------ -- Test the date medium converter. -- ------------------------------ procedure Test_Date_Medium_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.MEDIUM, ASF.Converters.Dates.DEFAULT, "Nov 19, 2011"); end Test_Date_Medium_Converter; -- ------------------------------ -- Test the date long converter. -- ------------------------------ procedure Test_Date_Long_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.LONG, ASF.Converters.Dates.DEFAULT, "November 19, 2011"); end Test_Date_Long_Converter; -- ------------------------------ -- Test the date full converter. -- ------------------------------ procedure Test_Date_Full_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.FULL, ASF.Converters.Dates.DEFAULT, "Saturday, November 19, 2011"); end Test_Date_Full_Converter; -- ------------------------------ -- Test the time short converter. -- ------------------------------ procedure Test_Time_Short_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.SHORT, "03:04"); end Test_Time_Short_Converter; -- ------------------------------ -- Test the time short converter. -- ------------------------------ procedure Test_Time_Medium_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.MEDIUM, "03:04"); end Test_Time_Medium_Converter; -- ------------------------------ -- Test the time long converter. -- ------------------------------ procedure Test_Time_Long_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.LONG, "03:04:05"); end Test_Time_Long_Converter; end ASF.Converters.Tests;
Add tests to verify the To_Object function and parse a string into a date
Add tests to verify the To_Object function and parse a string into a date
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
5ccd981b12081a9ca12629558582e3e8f301ce14
src/wiki-streams-builders.ads
src/wiki-streams-builders.ads
----------------------------------------------------------------------- -- wiki-streams-builders -- Wiki writer to a string builder -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; -- == Writer interfaces == -- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write -- their outputs. -- package Wiki.Streams.Builders is type Output_Builder_Stream is limited new Output_Stream with private; type Output_Builder_Stream_Access is access all Output_Builder_Stream'Class; -- Write the content to the string builder. overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wide_Wide_Character); -- Write the string to the string builder. procedure Write_String (Stream : in out Output_Builder_Stream; Content : in STring); -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. procedure Iterate (Source : in Output_Builder_Stream; Process : not null access procedure (Chunk : in Wide_Wide_String)); -- Convert what was collected in the writer builder to a string and return it. function To_String (Source : in Output_Builder_Stream) return String; private BLOCK_SIZE : constant Positive := 512; type Output_Builder_Stream is limited new Output_Stream with record Content : Wiki.Strings.Bstring (BLOCK_SIZE); end record; end Wiki.Streams.Builders;
----------------------------------------------------------------------- -- wiki-streams-builders -- Wiki writer to a string builder -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; -- === Output Builder Stream == -- The <tt>Output_Builder_Stream</tt> is a concrete in-memory output stream. -- It collects the output in a <tt>Wiki.Strings.Bstring</tt> object and the -- content can be retrieved at the end by using the <tt>To_String</tt> -- or <tt>Iterate</tt> operation. package Wiki.Streams.Builders is type Output_Builder_Stream is limited new Output_Stream with private; type Output_Builder_Stream_Access is access all Output_Builder_Stream'Class; -- Write the content to the string builder. overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wiki.Strings.WString); -- Write a single character to the string builder. overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wiki.Strings.WChar); -- Write the string to the string builder. procedure Write_String (Stream : in out Output_Builder_Stream; Content : in String); -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. procedure Iterate (Source : in Output_Builder_Stream; Process : not null access procedure (Chunk : in Wiki.Strings.WString)); -- Convert what was collected in the writer builder to a string and return it. function To_String (Source : in Output_Builder_Stream) return String; private BLOCK_SIZE : constant Positive := 512; type Output_Builder_Stream is limited new Output_Stream with record Content : Wiki.Strings.Bstring (BLOCK_SIZE); end record; end Wiki.Streams.Builders;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
9181e9386e2930f6fa0972bbd3203407c4031959
symbolica/ada/src/Symbolica.adb
symbolica/ada/src/Symbolica.adb
with Ada.Text_IO; with Ada.Command_Line; procedure Symbolica is NumColors : constant := 4; NumSymbols : constant := 3; Length : constant := 5; Width : constant := 5; package IO renames Ada.Text_IO; type Color_T is new Natural range 0 .. NumColors - 1; type Symbol_T is new Natural range 0 .. NumSymbols - 1; type Column_T is new Natural range 1 .. Length; type Row_T is new Natural range 1 .. Width; type Tile_T is record Color : Color_T; Symbol : Symbol_T; end record; type Board_T is Array(Row_T, Column_T) of Tile_T; type Count_T is Array(Color_T, Symbol_T) of Natural; -- colors : constant Array(Color_T) of Character := ('R', 'B'); -- symbols : constant Array(Symbol_T) of Character := ('n', 'a'); colors : constant Array(Color_T) of Character := ('R', 'B', 'G', 'Y'); symbols : constant Array(Symbol_T) of Character := ('a', 'g', 'c'); original_board, best_board, board : Board_T; best_distance : Natural := Length * Width; total_solutions : Natural := 0; iterations : Natural := 0; tile_count : Count_T := (others => (others => 0)); Not_In : exception; function GetColor(c: Character) return Color_T is begin for color in Color_T'Range loop if colors(color) = c then return color; end if; end loop; raise Not_In; end GetColor; function GetSymbol(s: Character) return Symbol_T is begin for symbol in Symbol_T'Range loop if symbols(symbol) = s then return symbol; end if; end loop; raise Not_In; end GetSymbol; function TileImage(tile : Tile_T) return String is begin return (colors(tile.Color), symbols(tile.Symbol)); end TileImage; procedure PrintBoard(b : Board_T) is begin for r in Row_T loop for c in Column_T loop IO.Put(TileImage(b(r,c)) & " "); end loop; IO.New_Line; end loop; end PrintBoard; procedure ReadBoard(filename: in String; b : out Board_T) is f : IO.File_Type; c,s : Character; eol : Boolean; begin IO.Open(f, IO.In_File, filename); for row in Row_T'Range loop for col in Column_T'Range loop IO.Get(f, c); IO.Get(f, s); b(row, col) := (GetColor(c), GetSymbol(s)); loop IO.Look_Ahead(f,c,eol); exit when eol or else c /= ' '; IO.Get(f, c); end loop; end loop; end loop; IO.Put_Line("Read in original Board"); PrintBoard(b); end ReadBoard; procedure CompareBoards is distance : Natural := 0; chain : Natural := 0; waiting : Array(Color_T, Symbol_T, Color_T, Symbol_T) of Natural := (others => (others => (others => (others => 0)))); begin total_solutions := total_solutions + 1; for row in Row_T'Range loop for col in Column_T'Range loop declare o : Tile_T renames original_board(row, col); b : Tile_T renames board(row, col); w : natural renames waiting(o.Color, o.Symbol, b.Color, b.Symbol); ow : natural renames waiting(b.Color, b.Symbol, o.Color, o.Symbol); begin if o.Color /= b.Color or else o.Symbol /= b.Symbol then if ow > 0 then ow := ow - 1; chain := chain - 1; distance := distance + 1; else chain := chain + 1; w := w + 1; end if; end if; end; end loop; end loop; if chain > 0 then distance := distance + chain - 1; end if; if distance < best_distance then best_board := board; best_distance := distance; end if; end CompareBoards; procedure Solve(row : Row_T; col : Column_T) is procedure NextSolve(c : Color_T; s : Symbol_T) is tc : Natural renames tile_count(c, s); begin if tc = 0 then return; end if; board(row, col) := (c, s); if col = Column_T'Last then if row = Row_T'Last then CompareBoards; else tc := tc - 1; Solve(row + 1, 1); tc := tc + 1; end if; else tc := tc - 1; Solve(row, col + 1); tc := tc + 1; end if; end NextSolve; pragma inline(NextSolve); begin iterations := iterations + 1; if row = 1 then declare left : Tile_T renames board(row, col - 1); begin for color in Color_T'Range loop if color /= left.Color then NextSolve(color, left.Symbol); end if; end loop; for symbol in Symbol_T'Range loop if symbol /= left.Symbol then NextSolve(left.Color, symbol); end if; end loop; end; elsif col = 1 then declare above : Tile_T renames board(row - 1, col); begin for color in Color_T'Range loop if color /= above.Color then NextSolve(color, above.Symbol); end if; end loop; for symbol in Symbol_T'Range loop if symbol /= above.Symbol then NextSolve(above.Color, symbol); end if; end loop; end; else declare left : Tile_T renames board(row, col -1); above : Tile_T renames board(row - 1, col); begin if left.Color = above.Color then for symbol in Symbol_T'Range loop if symbol /= left.Symbol and then symbol /= above.Symbol then NextSolve(left.Color, symbol); end if; end loop; elsif left.Symbol = above.Symbol then for color in Color_T'Range loop if color /= left.Color and then color /= above.Color then NextSolve(color, left.Symbol); end if; end loop; else NextSolve(left.Color, above.Symbol); NextSolve(above.Color, left.Symbol); end if; end; end if; end Solve; begin ReadBoard(Ada.Command_Line.Argument(1), original_board); for row in Row_T'Range loop for col in Column_T'Range loop declare tile : constant Tile_T := original_board(row, col); begin tile_count(tile.Color, tile.Symbol) := tile_count(tile.Color, tile.Symbol) + 1; end; end loop; end loop; for color in Color_T'Range loop for symbol in Symbol_T'Range loop board(1, 1) := (color, symbol); Solve(1, 2); end loop; end loop; IO.Put_Line("Total Iterations" & Natural'Image(iterations)); IO.Put_Line("Total Solutions found:" & Natural'Image(total_solutions)); IO.Put_Line("Total Swaps: " & Natural'Image(best_distance)); PrintBoard(best_board); end Symbolica;
with Ada.Text_IO; with Ada.Command_Line; procedure Symbolica is NumColors : constant := 4; NumSymbols : constant := 3; Length : constant := 5; Width : constant := 5; package IO renames Ada.Text_IO; type Color_T is new Natural range 0 .. NumColors - 1; type Symbol_T is new Natural range 0 .. NumSymbols - 1; type Column_T is new Natural range 1 .. Length; type Row_T is new Natural range 1 .. Width; type Tile_T is record Color : Color_T; Symbol : Symbol_T; end record; type Board_T is Array(Row_T, Column_T) of Tile_T; type Count_T is Array(Color_T, Symbol_T) of Natural; colors : constant Array(Color_T) of Character := ('R', 'B', 'G', 'Y'); symbols : constant Array(Symbol_T) of Character := ('a', 'g', 'c'); original_board, best_board, board : Board_T; best_distance : Natural := Length * Width; total_solutions : Natural := 0; iterations : Natural := 0; tile_count : Count_T := (others => (others => 0)); Not_In : exception; function GetColor(c: Character) return Color_T is begin for color in Color_T'Range loop if colors(color) = c then return color; end if; end loop; raise Not_In; end GetColor; function GetSymbol(s: Character) return Symbol_T is begin for symbol in Symbol_T'Range loop if symbols(symbol) = s then return symbol; end if; end loop; raise Not_In; end GetSymbol; function TileImage(tile : Tile_T) return String is begin return (colors(tile.Color), symbols(tile.Symbol)); end TileImage; procedure PrintBoard(b : Board_T) is begin for r in Row_T loop for c in Column_T loop IO.Put(TileImage(b(r,c)) & " "); end loop; IO.New_Line; end loop; end PrintBoard; procedure ReadBoard(filename: in String; b : out Board_T) is f : IO.File_Type; c,s : Character; eol : Boolean; begin IO.Open(f, IO.In_File, filename); for row in Row_T'Range loop for col in Column_T'Range loop IO.Get(f, c); IO.Get(f, s); b(row, col) := (GetColor(c), GetSymbol(s)); loop IO.Look_Ahead(f,c,eol); exit when eol or else c /= ' '; IO.Get(f, c); end loop; end loop; end loop; IO.Put_Line("Read in original Board"); PrintBoard(b); end ReadBoard; procedure CompareBoards is distance : Natural := 0; chain : Natural := 0; waiting : Array(Color_T, Symbol_T, Color_T, Symbol_T) of Natural := (others => (others => (others => (others => 0)))); begin total_solutions := total_solutions + 1; for row in Row_T'Range loop for col in Column_T'Range loop declare o : Tile_T renames original_board(row, col); b : Tile_T renames board(row, col); w : natural renames waiting(o.Color, o.Symbol, b.Color, b.Symbol); ow : natural renames waiting(b.Color, b.Symbol, o.Color, o.Symbol); begin if o.Color /= b.Color or else o.Symbol /= b.Symbol then if ow > 0 then ow := ow - 1; chain := chain - 1; distance := distance + 1; else chain := chain + 1; w := w + 1; end if; end if; end; end loop; end loop; if chain > 0 then distance := distance + chain - 1; end if; if distance < best_distance then best_board := board; best_distance := distance; end if; end CompareBoards; procedure Solve(row : Row_T; col : Column_T) is procedure NextSolve(c : Color_T; s : Symbol_T) is tc : Natural renames tile_count(c, s); begin if tc = 0 then return; end if; board(row, col) := (c, s); if col = Column_T'Last then if row = Row_T'Last then CompareBoards; else tc := tc - 1; Solve(row + 1, 1); tc := tc + 1; end if; else tc := tc - 1; Solve(row, col + 1); tc := tc + 1; end if; end NextSolve; pragma inline(NextSolve); begin iterations := iterations + 1; if row = 1 then declare left : Tile_T renames board(row, col - 1); begin for color in Color_T'Range loop if color /= left.Color then NextSolve(color, left.Symbol); end if; end loop; for symbol in Symbol_T'Range loop if symbol /= left.Symbol then NextSolve(left.Color, symbol); end if; end loop; end; elsif col = 1 then declare above : Tile_T renames board(row - 1, col); begin for color in Color_T'Range loop if color /= above.Color then NextSolve(color, above.Symbol); end if; end loop; for symbol in Symbol_T'Range loop if symbol /= above.Symbol then NextSolve(above.Color, symbol); end if; end loop; end; else declare left : Tile_T renames board(row, col -1); above : Tile_T renames board(row - 1, col); begin if left.Color = above.Color then for symbol in Symbol_T'Range loop if symbol /= left.Symbol and then symbol /= above.Symbol then NextSolve(left.Color, symbol); end if; end loop; elsif left.Symbol = above.Symbol then for color in Color_T'Range loop if color /= left.Color and then color /= above.Color then NextSolve(color, left.Symbol); end if; end loop; else NextSolve(left.Color, above.Symbol); NextSolve(above.Color, left.Symbol); end if; end; end if; end Solve; begin ReadBoard(Ada.Command_Line.Argument(1), original_board); for row in Row_T'Range loop for col in Column_T'Range loop declare tile : constant Tile_T := original_board(row, col); begin tile_count(tile.Color, tile.Symbol) := tile_count(tile.Color, tile.Symbol) + 1; end; end loop; end loop; for color in Color_T'Range loop for symbol in Symbol_T'Range loop board(1, 1) := (color, symbol); Solve(1, 2); end loop; end loop; IO.Put_Line("Total Iterations" & Natural'Image(iterations)); IO.Put_Line("Total Solutions found:" & Natural'Image(total_solutions)); IO.Put_Line("Total Swaps: " & Natural'Image(best_distance)); PrintBoard(best_board); end Symbolica;
Clean up formatting.
Clean up formatting.
Ada
unlicense
Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch
7dbe2c7d780055370fda0b6a0c7e1daa8b619ab6
src/gen-model-tables.adb
src/gen-model-tables.adb
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; package body Gen.Model.Tables is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" then declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : in Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; Name : constant String := To_String (From.Type_Name); begin if T /= null then return T.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : in Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T /= null then return To_String (T.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Returns the column type mapping. -- ------------------------------ function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access is use type Mappings.Mapping_Definition_Access; Result : Gen.Model.Mappings.Mapping_Definition_Access; begin Result := Gen.Model.Mappings.Find_Type (From.Type_Name); if Result = null then Result := From.Table.Package_Def.Find_Type (From.Type_Name); end if; return Result; end Get_Type_Mapping; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is use type Mappings.Mapping_Definition_Access; begin -- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); -- if O.Type_Mapping = null then -- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name); -- end if; null; end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; Table.Table_Name := Table.Type_Name; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Column.Table := Table'Unchecked_Access; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Table_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; package body Gen.Model.Tables is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" then declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then if Length (From.Sql_Type) > 0 then return Util.Beans.Objects.To_Object (From.Sql_Type); end if; declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return T.Get_Value ("name"); end; elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : in Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; Name : constant String := To_String (From.Type_Name); begin if T /= null then return T.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : in Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T /= null then return To_String (T.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Returns the column type mapping. -- ------------------------------ function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access is use type Mappings.Mapping_Definition_Access; Result : Gen.Model.Mappings.Mapping_Definition_Access; begin Result := Gen.Model.Mappings.Find_Type (From.Type_Name); if Result = null then Result := From.Table.Package_Def.Find_Type (From.Type_Name); end if; return Result; end Get_Type_Mapping; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is use type Mappings.Mapping_Definition_Access; begin -- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); -- if O.Type_Mapping = null then -- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name); -- end if; null; end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; Table.Table_Name := Table.Type_Name; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Column.Table := Table'Unchecked_Access; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Table_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
Use the type mapping for the SQL schema generation
Use the type mapping for the SQL schema generation
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
940856debf605c5eefe869a9ce361048187884cf
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; package body Gen.Artifacts.Docs.Markdown is function Has_Scheme (Link : in String) return Boolean; use Util.Log; Log : constant Loggers.Logger := 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 Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); 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 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 Text (Pos + 1) = '[' then Start := Pos + 1; Pos := Util.Strings.Index (Text, ']', Pos + 2); if Pos = 0 then if Is_Image (Text (Start - 1 .. Text'Last)) then Ada.Text_IO.Put (File, Text (Start - 1 .. Text'Last)); else Ada.Text_IO.Put (File, Text (Start - 1 .. 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 - 1 .. Pos - 1)); Ada.Text_IO.Put (")"); else Ada.Text_IO.Put (File, Text (Start - 1 .. Pos)); end if; Start := Pos + 1; 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, 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, ")"); 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, "```"); 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, Document); begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end Finish_Document; end Gen.Artifacts.Docs.Markdown;
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- 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; use Util.Log; Log : constant Loggers.Logger := 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 Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); 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)); -- Parse a markdown link format. if 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, "```"); 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, Document); begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end Finish_Document; end Gen.Artifacts.Docs.Markdown;
Fix the markdown image and link generation
Fix the markdown image and link generation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
1715fa6714919d27c46a890e5daf87ae6a8575bb
regtests/ado-sequences-tests.adb
regtests/ado-sequences-tests.adb
----------------------------------------------------------------------- -- ado-sequences-tests -- Test sequences factories -- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Drivers; with ADO.Sessions; with ADO.SQL; with Regtests.Simple.Model; with ADO.Sequences.Hilo; with ADO.Sessions.Sources; with ADO.Sessions.Factory; package body ADO.Sequences.Tests is use Util.Tests; type Test_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE) with record Version : Integer; Value : ADO.Identifier; Name : Ada.Strings.Unbounded.Unbounded_String; Select_Name : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Destroy (Object : access Test_Impl); overriding procedure Find (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Create (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); package Caller is new Util.Test_Caller (Test, "ADO.Sequences"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Sequences.Create", Test_Create_Factory'Access); end Add_Tests; -- Test creation of the sequence factory. -- This test revealed a memory leak if we failed to create a database connection. procedure Test_Create_Factory (T : in out Test) is Seq_Factory : ADO.Sequences.Factory; Obj : Test_Impl; Factory : aliased ADO.Sessions.Factory.Session_Factory; Controller : aliased ADO.Sessions.Sources.Data_Source; Prev_Id : Identifier := ADO.NO_IDENTIFIER; begin Seq_Factory.Set_Default_Generator (ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); begin Seq_Factory.Allocate (Obj); T.Assert (False, "No exception raised."); exception when ADO.Drivers.Connection_Error => null; -- Good! An exception is expected because the session factory is empty. end; -- Make a real connection. Controller.Set_Connection (ADO.Drivers.Get_Config ("test.database")); Factory.Create (Controller); for I in 1 .. 1_000 loop Seq_Factory.Allocate (Obj); T.Assert (Obj.Get_Key_Value /= Prev_Id, "Invalid id was allocated"); Prev_Id := Obj.Get_Key_Value; end loop; end Test_Create_Factory; overriding procedure Destroy (Object : access Test_Impl) is begin null; end Destroy; overriding procedure Find (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is pragma Unreferenced (Object, Session, Query); begin Found := False; end Find; overriding procedure Load (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class) is begin null; end Load; overriding procedure Save (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Save; overriding procedure Delete (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Delete; overriding procedure Create (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Create; end ADO.Sequences.Tests;
----------------------------------------------------------------------- -- ado-sequences-tests -- Test sequences factories -- Copyright (C) 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Drivers; with ADO.Sessions; with ADO.SQL; with Regtests.Simple.Model; with ADO.Sequences.Hilo; with ADO.Sessions.Sources; with ADO.Sessions.Factory; package body ADO.Sequences.Tests is type Test_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE) with record Version : Integer; Value : ADO.Identifier; Name : Ada.Strings.Unbounded.Unbounded_String; Select_Name : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Destroy (Object : access Test_Impl); overriding procedure Find (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Create (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class); package Caller is new Util.Test_Caller (Test, "ADO.Sequences"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Sequences.Create", Test_Create_Factory'Access); end Add_Tests; -- Test creation of the sequence factory. -- This test revealed a memory leak if we failed to create a database connection. procedure Test_Create_Factory (T : in out Test) is Seq_Factory : ADO.Sequences.Factory; Obj : Test_Impl; Factory : aliased ADO.Sessions.Factory.Session_Factory; Controller : aliased ADO.Sessions.Sources.Data_Source; Prev_Id : Identifier := ADO.NO_IDENTIFIER; begin Seq_Factory.Set_Default_Generator (ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); begin Seq_Factory.Allocate (Obj); T.Assert (False, "No exception raised."); exception when ADO.Drivers.Connection_Error => null; -- Good! An exception is expected because the session factory is empty. end; -- Make a real connection. Controller.Set_Connection (ADO.Drivers.Get_Config ("test.database")); Factory.Create (Controller); for I in 1 .. 1_000 loop Seq_Factory.Allocate (Obj); T.Assert (Obj.Get_Key_Value /= Prev_Id, "Invalid id was allocated"); Prev_Id := Obj.Get_Key_Value; end loop; end Test_Create_Factory; overriding procedure Destroy (Object : access Test_Impl) is begin null; end Destroy; overriding procedure Find (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is pragma Unreferenced (Object, Session, Query); begin Found := False; end Find; overriding procedure Load (Object : in out Test_Impl; Session : in out ADO.Sessions.Session'Class) is begin null; end Load; overriding procedure Save (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Save; overriding procedure Delete (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Delete; overriding procedure Create (Object : in out Test_Impl; Session : in out ADO.Sessions.Master_Session'Class) is begin null; end Create; end ADO.Sequences.Tests;
Remove unecessary use clause
Remove unecessary use clause
Ada
apache-2.0
stcarrez/ada-ado
0a9479681a7a0c5ff3761e2775f4a7a78740e468
src/mysql/ado-drivers-connections-mysql.adb
src/mysql/ado-drivers-connections-mysql.adb
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Ada.Finalization; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Mysql; with ADO.C; with Mysql.Lib; use Mysql.Lib; package body ADO.Drivers.Connections.Mysql is use ADO.Statements.Mysql; use Util.Log; use Interfaces.C; pragma Linker_Options (MYSQL_LIB_NAME); Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql"); Driver_Name : aliased constant String := "mysql"; Driver : aliased Mysql_Driver; -- This is a little bit overkill but this is portable. We must call the 'mysql_thread_end' -- operation before a task/thread terminates. The only way to do it is to setup a task -- attribute which an object that has a finalization procedure. -- -- The task cleaner attribute is set on tasks that call the 'mysql_connect' operation only. type Mysql_Task_Cleaner is new Ada.Finalization.Controlled with null record; -- Invoke the 'mysql_task_end' to release the storage allocated by mysql for the current task. overriding procedure Finalize (Object : in out Mysql_Task_Cleaner); Cleaner : Mysql_Task_Cleaner; package Mysql_Task_Attribute is new Ada.Task_Attributes (Mysql_Task_Cleaner, Cleaner); -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Autocommit then Database.Execute ("set autocommit=0"); Database.Autocommit := False; end if; Database.Execute ("start transaction;"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is Result : char; begin Result := mysql_commit (Database.Server); if Result /= nul then raise DB_Error with "Cannot commit transaction"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is Result : char; begin Result := mysql_rollback (Database.Server); if Result /= nul then raise DB_Error with "Cannot rollback transaction"; end if; end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin null; end Load_Schema; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = null then Log.Error ("Database connection is not open"); end if; Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", int'Image (Result)); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin Log.Info ("Closing connection {0}", Database.Name); if Database.Server /= null then mysql_close (Database.Server); Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the mysql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}", Database.Name); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- mysql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : out ADO.Drivers.Connections.Database_Connection_Access) is pragma Unreferenced (D); Server : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server); Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database); Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user")); Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password")); Socket : ADO.C.String_Ptr; Port : unsigned := unsigned (Config.Port); Flags : constant unsigned_long := 0; Connection : Mysql_Access; Socket_Path : constant String := Config.Get_Property ("socket"); Database : constant Database_Connection_Access := new Database_Connection; begin if Socket_Path /= "" then ADO.C.Set_String (Socket, Socket_Path); end if; if Port = 0 then Port := 3306; end if; Log.Info ("Connecting to {0}:{1}", To_String (Config.Server), To_String (Config.Database)); Log.Debug ("user={0} password={1}", Config.Get_Property ("user"), Config.Get_Property ("password")); Connection := mysql_init (null); Mysql_Task_Attribute.Set_Value (Cleaner); Database.Server := mysql_real_connect (Connection, ADO.C.To_C (Server), ADO.C.To_C (Login), ADO.C.To_C (Password), ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags); if Database.Server = null then declare Message : constant String := Strings.Value (Mysql_Error (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.URI), Message); mysql_close (Connection); raise Connection_Error with "Cannot connect to mysql server: " & Message; end; end if; Database.Name := Config.Database; Database.Count := 1; Result := Database.all'Access; end Create_Connection; -- ------------------------------ -- Initialize the Mysql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing mysql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Mysql driver. -- ------------------------------ overriding procedure Finalize (D : in out Mysql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the mysql driver"); mysql_server_end; end Finalize; -- ------------------------------ -- Invoke the 'mysql_task_end' to release the storage allocated by mysql for the current task. -- ------------------------------ overriding procedure Finalize (Object : in out Mysql_Task_Cleaner) is pragma Unreferenced (Object); begin mysql_thread_end; end Finalize; end ADO.Drivers.Connections.Mysql;
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- 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.Task_Identification; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Mysql; with ADO.C; with Mysql.Lib; use Mysql.Lib; package body ADO.Drivers.Connections.Mysql is use ADO.Statements.Mysql; use Util.Log; use Interfaces.C; pragma Linker_Options (MYSQL_LIB_NAME); Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql"); Driver_Name : aliased constant String := "mysql"; Driver : aliased Mysql_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Autocommit then Database.Execute ("set autocommit=0"); Database.Autocommit := False; end if; Database.Execute ("start transaction;"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is Result : char; begin Result := mysql_commit (Database.Server); if Result /= nul then raise DB_Error with "Cannot commit transaction"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is Result : char; begin Result := mysql_rollback (Database.Server); if Result /= nul then raise DB_Error with "Cannot rollback transaction"; end if; end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin null; end Load_Schema; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = null then Log.Error ("Database connection is not open"); end if; Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", int'Image (Result)); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin Log.Info ("Closing connection {0}", Database.Name); if Database.Server /= null then mysql_close (Database.Server); Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the mysql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}", Database.Name); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- mysql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : out ADO.Drivers.Connections.Database_Connection_Access) is pragma Unreferenced (D); Server : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server); Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database); Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user")); Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password")); Socket : ADO.C.String_Ptr; Port : unsigned := unsigned (Config.Port); Flags : constant unsigned_long := 0; Connection : Mysql_Access; Socket_Path : constant String := Config.Get_Property ("socket"); Database : constant Database_Connection_Access := new Database_Connection; begin if Socket_Path /= "" then ADO.C.Set_String (Socket, Socket_Path); end if; if Port = 0 then Port := 3306; end if; Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), To_String (Config.Server), To_String (Config.Database)); Log.Debug ("user={0} password={1}", Config.Get_Property ("user"), Config.Get_Property ("password")); Connection := mysql_init (null); Database.Server := mysql_real_connect (Connection, ADO.C.To_C (Server), ADO.C.To_C (Login), ADO.C.To_C (Password), ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags); if Database.Server = null then declare Message : constant String := Strings.Value (Mysql_Error (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.URI), Message); mysql_close (Connection); raise Connection_Error with "Cannot connect to mysql server: " & Message; end; end if; Database.Name := Config.Database; Database.Count := 1; Result := Database.all'Access; end Create_Connection; -- ------------------------------ -- Initialize the Mysql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing mysql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Mysql driver. -- ------------------------------ overriding procedure Finalize (D : in out Mysql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the mysql driver"); mysql_server_end; end Finalize; end ADO.Drivers.Connections.Mysql;
Revert r326 because Ada task attribute cleaner is not executed by the thread which sets the TLS data. Hence, invoking mysql_thread_end is done but not by the good thread. Fixed the issue by patching libmysqlclient (See MySQL bug http://bugs.mysql.com/bug.php?id=66740)
Revert r326 because Ada task attribute cleaner is not executed by the thread which sets the TLS data. Hence, invoking mysql_thread_end is done but not by the good thread. Fixed the issue by patching libmysqlclient (See MySQL bug http://bugs.mysql.com/bug.php?id=66740)
Ada
apache-2.0
stcarrez/ada-ado
0a5f22e4eb88b49cf0d00859de69cad96c1b6ab0
src/security-policies-roles.adb
src/security-policies-roles.adb
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is use Util.Log; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions"); -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- 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 is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This 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. -- ------------------------------ procedure Set_Reader_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config_Mapper.Set_Context (Reader, Config); end Set_Reader_Config; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); 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 Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- 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 is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This 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. -- ------------------------------ procedure Set_Reader_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config_Mapper.Set_Context (Reader, Config); end Set_Reader_Config; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
Update the comments and logger
Update the comments and logger
Ada
apache-2.0
stcarrez/ada-security
a5031e1b0b3243edb2b05ac2f12fbfd9f8c80783
src/natools-web-simple_pages.adb
src/natools-web-simple_pages.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Simple_Pages; with Natools.Web.Error_Pages; with Natools.Web.Exchanges; with Natools.Web.Fallback_Render; package body Natools.Web.Simple_Pages is procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom); procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Read_Page is new S_Expressions.Interpreter_Loop (Page_Data, Meaningless_Type, Execute); procedure Render_Page is new S_Expressions.Interpreter_Loop (Sites.Exchange, Page_Data, Render, Append); --------------------------- -- Page Data Constructor -- --------------------------- procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); package Components renames Natools.Static_Maps.Web.Simple_Pages; begin case Components.To_Component (S_Expressions.To_String (Name)) is when Components.Error => Log (Severities.Error, "Unknown page component """ & S_Expressions.To_String (Name) & '"'); when Components.Comment_List => Data.Comment_List.Set (Arguments); when Components.Dates => Containers.Set_Dates (Data.Dates, Arguments); when Components.Elements => Containers.Set_Expressions (Data.Elements, Arguments); when Components.Tags => Tags.Append (Data.Tags, Arguments); end case; end Execute; ------------------- -- Page Renderer -- ------------------- procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom) is pragma Unreferenced (Page); begin Exchange.Append (Data); end Append; procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class); procedure Render_Date (Log_Error : in Boolean); procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Page); end Re_Enter; procedure Render_Date (Log_Error : in Boolean) is begin if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Cursor : constant Containers.Date_Maps.Cursor := Page.Dates.Find (Arguments.Current_Atom); begin if not Containers.Date_Maps.Has_Element (Cursor) then if Log_Error then Log (Severities.Error, "Unable to find date """ & S_Expressions.To_String (Arguments.Current_Atom) & """ in page date map"); end if; return; end if; Arguments.Next; declare Item : constant Containers.Date := Containers.Date_Maps.Element (Cursor); begin S_Expressions.Templates.Dates.Render (Exchange, Arguments, Item.Time, Item.Offset); end; end; end if; end Render_Date; package Commands renames Natools.Static_Maps.Web.Simple_Pages; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown_Command => Fallback_Render (Exchange, Name, Arguments, "simple page", Re_Enter'Access, Page.Elements); when Commands.Comment_List => Comments.Render (Exchange, Page.Comment_List, Arguments); when Commands.Date => Render_Date (True); when Commands.My_Tags => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Prefix : constant S_Expressions.Atom := Arguments.Current_Atom; begin Arguments.Next; Tags.Render (Exchange, Page.Tags, Exchange.Site.Get_Tags, Prefix, Arguments); end; end if; when Commands.If_No_Date => if Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Page.Dates.Contains (Arguments.Current_Atom) then Arguments.Next; Render_Page (Arguments, Exchange, Page); end if; when Commands.Optional_Date => Render_Date (False); when Commands.Path => Exchange.Append (Page.Web_Path.Query); when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments, Page.Tags); end case; end Render; ------------------------- -- Page_Data Interface -- ------------------------- not overriding procedure Get_Element (Data : in Page_Data; Name : in S_Expressions.Atom; Element : out S_Expressions.Caches.Cursor; Found : out Boolean) is Cursor : constant Containers.Expression_Maps.Cursor := Data.Elements.Find (Name); begin Found := Containers.Expression_Maps.Has_Element (Cursor); if Found then Element := Containers.Expression_Maps.Element (Cursor); end if; end Get_Element; ---------------------- -- Public Interface -- ---------------------- function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data; Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); begin Page.Self := Tags.Visible_Access (Page); Read_Page (Expression, Page.all, Meaningless_Value); return Result; end Create; function Create (File_Path, Web_Path : in S_Expressions.Atom_Refs.Immutable_Reference) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data' (File_Path => File_Path, Web_Path => Web_Path, Tags => <>, Self => null, Comment_List | Elements | Dates => <>); Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); begin Page.Self := Tags.Visible_Access (Page); Create_Page : declare Reader : Natools.S_Expressions.File_Readers.S_Reader := Natools.S_Expressions.File_Readers.Reader (S_Expressions.To_String (File_Path.Query)); begin Read_Page (Reader, Page.all, Meaningless_Value); end Create_Page; return Result; end Create; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Ref; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object.Ref.Query.Data.all); end Render; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Data; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object); end Render; overriding procedure Respond (Object : in out Page_Ref; Exchange : in out Sites.Exchange; Extra_Path : in S_Expressions.Atom) is use type S_Expressions.Offset; begin if Extra_Path'Length = 9 and then S_Expressions.To_String (Extra_Path) = "/comments" then Object.Ref.Update.Comment_List.Respond (Exchange, Extra_Path (Extra_Path'First + 9 .. Extra_Path'Last)); return; end if; if Extra_Path'Length > 0 then return; end if; declare Accessor : constant Data_Refs.Accessor := Object.Ref.Query; Expression : S_Expressions.Caches.Cursor; begin Check_Method : declare use Exchanges; Allowed : Boolean; begin Error_Pages.Check_Method (Exchange, (GET, HEAD), Allowed); if not Allowed then return; end if; end Check_Method; Expression := Exchange.Site.Get_Template (Accessor.Data.Elements, Expression, Exchange.Site.Default_Template, Lookup_Element => True, Lookup_Template => True, Lookup_Name => True); Render_Page (Expression, Exchange, Accessor.Data.all); end; end Respond; ----------------------- -- Page Constructors -- ----------------------- function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class is begin return Loader'(File_Path => S_Expressions.Atom_Ref_Constructors.Create (File)); end Create; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is Page : constant Page_Ref := Create (Object.File_Path, S_Expressions.Atom_Ref_Constructors.Create (Path)); begin Sites.Insert (Builder, Path, Page); Sites.Insert (Builder, Page.Get_Tags, Page); declare Mutator : constant Data_Refs.Mutator := Page.Ref.Update; begin Mutator.Comment_List.Load (Builder, Mutator.Self, Mutator.Web_Path); end; end Load; procedure Register_Loader (Site : in out Sites.Site) is begin Site.Register ("simple-page", Create'Access); end Register_Loader; end Natools.Web.Simple_Pages;
------------------------------------------------------------------------------ -- Copyright (c) 2014-2015, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Calendar; with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Simple_Pages; with Natools.Web.Error_Pages; with Natools.Web.Exchanges; with Natools.Web.Fallback_Render; package body Natools.Web.Simple_Pages is Expiration_Date_Key : constant S_Expressions.Atom := S_Expressions.To_Atom ("!expire"); procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom); procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Read_Page is new S_Expressions.Interpreter_Loop (Page_Data, Meaningless_Type, Execute); procedure Render_Page is new S_Expressions.Interpreter_Loop (Sites.Exchange, Page_Data, Render, Append); --------------------------- -- Page Data Constructor -- --------------------------- procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); package Components renames Natools.Static_Maps.Web.Simple_Pages; begin case Components.To_Component (S_Expressions.To_String (Name)) is when Components.Error => Log (Severities.Error, "Unknown page component """ & S_Expressions.To_String (Name) & '"'); when Components.Comment_List => Data.Comment_List.Set (Arguments); when Components.Dates => Containers.Set_Dates (Data.Dates, Arguments); when Components.Elements => Containers.Set_Expressions (Data.Elements, Arguments); when Components.Tags => Tags.Append (Data.Tags, Arguments); end case; end Execute; ------------------- -- Page Renderer -- ------------------- procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom) is pragma Unreferenced (Page); begin Exchange.Append (Data); end Append; procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class); procedure Render_Date (Log_Error : in Boolean); procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Page); end Re_Enter; procedure Render_Date (Log_Error : in Boolean) is begin if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Cursor : constant Containers.Date_Maps.Cursor := Page.Dates.Find (Arguments.Current_Atom); begin if not Containers.Date_Maps.Has_Element (Cursor) then if Log_Error then Log (Severities.Error, "Unable to find date """ & S_Expressions.To_String (Arguments.Current_Atom) & """ in page date map"); end if; return; end if; Arguments.Next; declare Item : constant Containers.Date := Containers.Date_Maps.Element (Cursor); begin S_Expressions.Templates.Dates.Render (Exchange, Arguments, Item.Time, Item.Offset); end; end; end if; end Render_Date; package Commands renames Natools.Static_Maps.Web.Simple_Pages; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown_Command => Fallback_Render (Exchange, Name, Arguments, "simple page", Re_Enter'Access, Page.Elements); when Commands.Comment_List => Comments.Render (Exchange, Page.Comment_List, Arguments); when Commands.Date => Render_Date (True); when Commands.My_Tags => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Prefix : constant S_Expressions.Atom := Arguments.Current_Atom; begin Arguments.Next; Tags.Render (Exchange, Page.Tags, Exchange.Site.Get_Tags, Prefix, Arguments); end; end if; when Commands.If_No_Date => if Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Page.Dates.Contains (Arguments.Current_Atom) then Arguments.Next; Render_Page (Arguments, Exchange, Page); end if; when Commands.Optional_Date => Render_Date (False); when Commands.Path => Exchange.Append (Page.Web_Path.Query); when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments, Page.Tags); end case; end Render; ------------------------- -- Page_Data Interface -- ------------------------- not overriding procedure Get_Element (Data : in Page_Data; Name : in S_Expressions.Atom; Element : out S_Expressions.Caches.Cursor; Found : out Boolean) is Cursor : constant Containers.Expression_Maps.Cursor := Data.Elements.Find (Name); begin Found := Containers.Expression_Maps.Has_Element (Cursor); if Found then Element := Containers.Expression_Maps.Element (Cursor); end if; end Get_Element; ---------------------- -- Public Interface -- ---------------------- function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data; Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); begin Page.Self := Tags.Visible_Access (Page); Read_Page (Expression, Page.all, Meaningless_Value); return Result; end Create; function Create (File_Path, Web_Path : in S_Expressions.Atom_Refs.Immutable_Reference) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data' (File_Path => File_Path, Web_Path => Web_Path, Tags => <>, Self => null, Comment_List | Elements | Dates => <>); Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); begin Page.Self := Tags.Visible_Access (Page); Create_Page : declare Reader : Natools.S_Expressions.File_Readers.S_Reader := Natools.S_Expressions.File_Readers.Reader (S_Expressions.To_String (File_Path.Query)); begin Read_Page (Reader, Page.all, Meaningless_Value); end Create_Page; return Result; end Create; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Ref; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object.Ref.Query.Data.all); end Render; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Data; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object); end Render; overriding procedure Respond (Object : in out Page_Ref; Exchange : in out Sites.Exchange; Extra_Path : in S_Expressions.Atom) is use type S_Expressions.Offset; begin if Extra_Path'Length = 9 and then S_Expressions.To_String (Extra_Path) = "/comments" then Object.Ref.Update.Comment_List.Respond (Exchange, Extra_Path (Extra_Path'First + 9 .. Extra_Path'Last)); return; end if; if Extra_Path'Length > 0 then return; end if; declare Accessor : constant Data_Refs.Accessor := Object.Ref.Query; Expression : S_Expressions.Caches.Cursor; begin Check_Method : declare use Exchanges; Allowed : Boolean; begin Error_Pages.Check_Method (Exchange, (GET, HEAD), Allowed); if not Allowed then return; end if; end Check_Method; Expression := Exchange.Site.Get_Template (Accessor.Data.Elements, Expression, Exchange.Site.Default_Template, Lookup_Element => True, Lookup_Template => True, Lookup_Name => True); Render_Page (Expression, Exchange, Accessor.Data.all); end; end Respond; ----------------------- -- Page Constructors -- ----------------------- function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class is begin return Loader'(File_Path => S_Expressions.Atom_Ref_Constructors.Create (File)); end Create; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is Page : constant Page_Ref := Create (Object.File_Path, S_Expressions.Atom_Ref_Constructors.Create (Path)); begin Expiration_Check : declare use type Ada.Calendar.Time; Accessor : constant Data_Refs.Accessor := Page.Ref.Query; Cursor : constant Containers.Date_Maps.Cursor := Accessor.Dates.Find (Expiration_Date_Key); begin if Containers.Date_Maps.Has_Element (Cursor) and then Containers.Date_Maps.Element (Cursor).Time < Ada.Calendar.Clock then return; end if; end Expiration_Check; Sites.Insert (Builder, Path, Page); Sites.Insert (Builder, Page.Get_Tags, Page); declare Mutator : constant Data_Refs.Mutator := Page.Ref.Update; begin Mutator.Comment_List.Load (Builder, Mutator.Self, Mutator.Web_Path); end; end Load; procedure Register_Loader (Site : in out Sites.Site) is begin Site.Register ("simple-page", Create'Access); end Register_Loader; end Natools.Web.Simple_Pages;
add a special date used to mark page expiration time
simple_pages: add a special date used to mark page expiration time
Ada
isc
faelys/natools-web,faelys/natools-web
8f125708c7a917fe2e51186a5bfd70424a09676a
src/security-openid-servlets.adb
src/security-openid-servlets.adb
----------------------------------------------------------------------- -- security-openid-servlets - Servlets for OpenID 2.0 Authentication -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Sessions; with Util.Beans.Objects; with Util.Beans.Objects.Records; with Util.Log.Loggers; package body Security.Openid.Servlets is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Openid.Servlets"); -- Make a package to store the Association in the session. package Association_Bean is new Util.Beans.Objects.Records (Security.Openid.Association); subtype Association_Access is Association_Bean.Element_Type_Access; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Openid_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class) is begin null; end Initialize; -- Property name that specifies the OpenID callback URL. OPENID_VERIFY_URL : constant String := "openid.callback_url"; -- Property name that specifies the realm. OPENID_REALM : constant String := "openid.realm"; -- Name of the session attribute which holds information about the active authentication. OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc"; procedure Initialize (Server : in Openid_Servlet; Manager : in out Security.Openid.Manager) is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; Callback_URI : constant String := Ctx.Get_Init_Parameter (OPENID_VERIFY_URL); Realm : constant String := Ctx.Get_Init_Parameter (OPENID_REALM); begin Manager.Initialize (Return_To => Callback_URI, Name => Realm); end Initialize; function Get_Provider_URL (Server : in Request_Auth_Servlet; Request : in ASF.Requests.Request'Class) return String is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; URI : constant String := Request.Get_Path_Info; begin if URI'Length = 0 then return ""; end if; Log.Info ("OpenID authentication with {0}", URI); return Ctx.Get_Init_Parameter ("openid.provider." & URI (URI'First + 1 .. URI'Last)); end Get_Provider_URL; -- ------------------------------ -- Proceed to the OpenID authentication with an OpenID provider. -- Find the OpenID provider URL and starts the discovery, association phases -- during which a private key is obtained from the OpenID provider. -- After OpenID discovery and association, the user will be redirected to -- the OpenID provider. -- ------------------------------ procedure Do_Get (Server : in Request_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Provider : constant String := Server.Get_Provider_URL (Request); begin Log.Info ("Request OpenId authentication to {0}", Provider); if Provider'Length = 0 then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; declare Mgr : Security.Openid.Manager; OP : Security.Openid.End_Point; Bean : constant Util.Beans.Objects.Object := Association_Bean.Create; Assoc : constant Association_Access := Association_Bean.To_Element_Access (Bean); begin Server.Initialize (Mgr); -- Yadis discovery (get the XRDS file). Mgr.Discover (Provider, OP); -- Associate to the OpenID provider and get an end-point with a key. Mgr.Associate (OP, Assoc.all); -- Save the association in the HTTP session and -- redirect the user to the OpenID provider. declare Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); Session : ASF.Sessions.Session := Request.Get_Session (Create => True); begin Log.Info ("Redirect to auth URL: {0}", Auth_URL); Response.Send_Redirect (Location => Auth_URL); Session.Set_Attribute (Name => OPENID_ASSOC_ATTRIBUTE, Value => Bean); end; end; end Do_Get; -- ------------------------------ -- Verify the authentication result that was returned by the OpenID provider. -- If the authentication succeeded and the signature was correct, sets a -- user principals on the session. -- ------------------------------ procedure Do_Get (Server : in Verify_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Session : ASF.Sessions.Session := Request.Get_Session (Create => False); Bean : constant Util.Beans.Objects.Object := Session.Get_Attribute (OPENID_ASSOC_ATTRIBUTE); Mgr : Security.Openid.Manager; Assoc : Association_Access; Auth : Security.Openid.Authentication; Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; begin Log.Info ("Verify openid authentication"); -- Cleanup the session and drop the association end point. Session.Remove_Attribute (OPENID_ASSOC_ATTRIBUTE); if Util.Beans.Objects.Is_Null (Bean) then Log.Warn ("Verify openid request without active session"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Assoc := Association_Bean.To_Element_Access (Bean); Server.Initialize (Mgr); -- Verify that what we receive through the callback matches the association key. Mgr.Verify (Assoc.all, Request, Auth); if Get_Status (Auth) /= AUTHENTICATED then Log.Info ("Authentication has failed"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Log.Info ("Authentication succeeded for {0}", Get_Email (Auth)); -- Get a user principal and set it on the session. declare User : ASF.Principals.Principal_Access; URL : constant String := Ctx.Get_Init_Parameter ("openid.success_url"); begin Verify_Auth_Servlet'Class (Server).Create_Principal (Auth, User); Session.Set_Principal (User); Log.Info ("Redirect user to success URL: {0}", URL); Response.Send_Redirect (Location => URL); end; end Do_Get; -- ------------------------------ -- Create a principal object that correspond to the authenticated user identified -- by the <b>Auth</b> information. The principal will be attached to the session -- and will be destroyed when the session is closed. -- ------------------------------ procedure Create_Principal (Server : in Verify_Auth_Servlet; Auth : in Authentication; Result : out ASF.Principals.Principal_Access) is pragma Unreferenced (Server); P : constant Principal_Access := new Principal; begin P.Auth := Auth; Result := P.all'Access; end Create_Principal; end Security.Openid.Servlets;
----------------------------------------------------------------------- -- security-openid-servlets - Servlets for OpenID 2.0 Authentication -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Sessions; with Util.Beans.Objects; with Util.Beans.Objects.Records; with Util.Log.Loggers; package body Security.Openid.Servlets is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Openid.Servlets"); -- Make a package to store the Association in the session. package Association_Bean is new Util.Beans.Objects.Records (Security.Openid.Association); subtype Association_Access is Association_Bean.Element_Type_Access; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Openid_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class) is begin null; end Initialize; -- Property name that specifies the OpenID callback URL. OPENID_VERIFY_URL : constant String := "openid.callback_url"; -- Property name that specifies the realm. OPENID_REALM : constant String := "openid.realm"; -- Name of the session attribute which holds information about the active authentication. OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc"; procedure Initialize (Server : in Openid_Servlet; Manager : in out Security.Openid.Manager) is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; Callback_URI : constant String := Ctx.Get_Init_Parameter (OPENID_VERIFY_URL); Realm : constant String := Ctx.Get_Init_Parameter (OPENID_REALM); begin Manager.Initialize (Return_To => Callback_URI, Name => Realm); end Initialize; function Get_Provider_URL (Server : in Request_Auth_Servlet; Request : in ASF.Requests.Request'Class) return String is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; URI : constant String := Request.Get_Path_Info; begin if URI'Length = 0 then return ""; end if; Log.Info ("OpenID authentication with {0}", URI); return Ctx.Get_Init_Parameter ("openid.provider." & URI (URI'First + 1 .. URI'Last)); end Get_Provider_URL; -- ------------------------------ -- Proceed to the OpenID authentication with an OpenID provider. -- Find the OpenID provider URL and starts the discovery, association phases -- during which a private key is obtained from the OpenID provider. -- After OpenID discovery and association, the user will be redirected to -- the OpenID provider. -- ------------------------------ procedure Do_Get (Server : in Request_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Provider : constant String := Server.Get_Provider_URL (Request); begin Log.Info ("Request OpenId authentication to {0}", Provider); if Provider'Length = 0 then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; declare Mgr : Security.Openid.Manager; OP : Security.Openid.End_Point; Bean : constant Util.Beans.Objects.Object := Association_Bean.Create; Assoc : constant Association_Access := Association_Bean.To_Element_Access (Bean); begin Server.Initialize (Mgr); -- Yadis discovery (get the XRDS file). Mgr.Discover (Provider, OP); -- Associate to the OpenID provider and get an end-point with a key. Mgr.Associate (OP, Assoc.all); -- Save the association in the HTTP session and -- redirect the user to the OpenID provider. declare Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); Session : ASF.Sessions.Session := Request.Get_Session (Create => True); begin Log.Info ("Redirect to auth URL: {0}", Auth_URL); Response.Send_Redirect (Location => Auth_URL); Session.Set_Attribute (Name => OPENID_ASSOC_ATTRIBUTE, Value => Bean); end; end; end Do_Get; -- ------------------------------ -- Verify the authentication result that was returned by the OpenID provider. -- If the authentication succeeded and the signature was correct, sets a -- user principals on the session. -- ------------------------------ procedure Do_Get (Server : in Verify_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Session : ASF.Sessions.Session := Request.Get_Session (Create => False); Bean : Util.Beans.Objects.Object; Mgr : Security.Openid.Manager; Assoc : Association_Access; Auth : Security.Openid.Authentication; Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; begin Log.Info ("Verify openid authentication"); if not Session.Is_Valid then Log.Warn ("Session has expired during OpenID authentication process"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Bean := Session.Get_Attribute (OPENID_ASSOC_ATTRIBUTE); -- Cleanup the session and drop the association end point. Session.Remove_Attribute (OPENID_ASSOC_ATTRIBUTE); if Util.Beans.Objects.Is_Null (Bean) then Log.Warn ("Verify openid request without active session"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Assoc := Association_Bean.To_Element_Access (Bean); Server.Initialize (Mgr); -- Verify that what we receive through the callback matches the association key. Mgr.Verify (Assoc.all, Request, Auth); if Get_Status (Auth) /= AUTHENTICATED then Log.Info ("Authentication has failed"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Log.Info ("Authentication succeeded for {0}", Get_Email (Auth)); -- Get a user principal and set it on the session. declare User : ASF.Principals.Principal_Access; URL : constant String := Ctx.Get_Init_Parameter ("openid.success_url"); begin Verify_Auth_Servlet'Class (Server).Create_Principal (Auth, User); Session.Set_Principal (User); Log.Info ("Redirect user to success URL: {0}", URL); Response.Send_Redirect (Location => URL); end; end Do_Get; -- ------------------------------ -- Create a principal object that correspond to the authenticated user identified -- by the <b>Auth</b> information. The principal will be attached to the session -- and will be destroyed when the session is closed. -- ------------------------------ procedure Create_Principal (Server : in Verify_Auth_Servlet; Auth : in Authentication; Result : out ASF.Principals.Principal_Access) is pragma Unreferenced (Server); P : constant Principal_Access := new Principal; begin P.Auth := Auth; Result := P.all'Access; end Create_Principal; end Security.Openid.Servlets;
Verify that the session is valid before getting the association attribute
Verify that the session is valid before getting the association attribute
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
a1357e4008d017b280757525872115132332e2d0
regtests/util-processes-tests.adb
regtests/util-processes-tests.adb
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Strings.Vectors; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; with Util.Systems.Os; with Util.Processes.Tools; package body Util.Processes.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)", Test_Shell_Splitting_Pipe'Access); pragma Warnings (Off); if Util.Systems.Os.Directory_Separator /= '\' then Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); end if; pragma Warnings (On); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Tools.Execute", Test_Tools_Execute'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test shell splitting. -- ------------------------------ procedure Test_Shell_Splitting_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write 'b c d e f' test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Shell_Splitting_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; -- ------------------------------ -- Test the Tools.Execute operation. -- ------------------------------ procedure Test_Tools_Execute (T : in out Test) is List : Util.Strings.Vectors.Vector; Status : Integer; begin Tools.Execute (Command => "bin/util_test_process 23 write 'b c d e f' test_marker", Output => List, Status => Status); Util.Tests.Assert_Equals (T, 23, Status, "Invalid exit status"); Util.Tests.Assert_Equals (T, 2, Integer (List.Length), "Invalid output collected by Execute"); Util.Tests.Assert_Equals (T, "b c d e f", List.Element (1), ""); Util.Tests.Assert_Equals (T, "test_marker", List.Element (2), ""); end Test_Tools_Execute; end Util.Processes.Tests;
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 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 Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Strings.Vectors; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; with Util.Systems.Os; with Util.Processes.Tools; package body Util.Processes.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)", Test_Shell_Splitting_Pipe'Access); pragma Warnings (Off); if Util.Systems.Os.Directory_Separator /= '\' then Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); end if; pragma Warnings (On); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Tools.Execute", Test_Tools_Execute'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test shell splitting. -- ------------------------------ procedure Test_Shell_Splitting_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write ""b c d e f"" test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Shell_Splitting_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; -- ------------------------------ -- Test the Tools.Execute operation. -- ------------------------------ procedure Test_Tools_Execute (T : in out Test) is List : Util.Strings.Vectors.Vector; Status : Integer; begin Tools.Execute (Command => "bin/util_test_process 23 write ""b c d e f"" test_marker", Output => List, Status => Status); Util.Tests.Assert_Equals (T, 23, Status, "Invalid exit status"); Util.Tests.Assert_Equals (T, 2, Integer (List.Length), "Invalid output collected by Execute"); Util.Tests.Assert_Equals (T, "b c d e f", List.Element (1), ""); Util.Tests.Assert_Equals (T, "test_marker", List.Element (2), ""); end Test_Tools_Execute; end Util.Processes.Tests;
Fix unit test on windows: use " to quote command line arguments
Fix unit test on windows: use " to quote command line arguments
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
295f388373539f9405fb13f4049549dce3809464
src/asf-converters-dates.ads
src/asf-converters-dates.ads
----------------------------------------------------------------------- -- asf-converters-dates -- Date Converters -- Copyright (C) 2011, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Locales; with ASF.Components.Base; with ASF.Contexts.Faces; with ASF.Locales; -- The <b>ASF.Converters.Dates</b> defines the date converter to format a date object -- into a localized representation. -- -- See JSR 314 - JavaServer Faces Specification 9.4.3 <f:convertDateTime> -- (To_String is the JSF getAsString method and To_Object is the JSF getAsObject method) package ASF.Converters.Dates is type Style_Type is (DEFAULT, SHORT, MEDIUM, LONG, FULL); type Format_Type is (DATE, TIME, BOTH, CONVERTER_PATTERN, COMPONENT_FORMAT); -- ------------------------------ -- Converter -- ------------------------------ -- The <b>Date_Converter</b> translates the object value which holds an Ada.Calendar -- into a printable date representation. It translates a string into an Ada Calendar time. -- Unlike the Java implementation, the instance will be shared by multiple -- views and requests. type Date_Converter is new Converter with private; type Date_Converter_Access is access all Date_Converter'Class; -- Convert the object value into a string. The object value is associated -- with the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. function To_String (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in Util.Beans.Objects.Object) return String; -- Convert the date string into an object for the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. function To_Object (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in String) return Util.Beans.Objects.Object; -- Get the date format pattern that must be used for formatting a date on the given component. function Get_Pattern (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Bundle : in ASF.Locales.Bundle; Component : in ASF.Components.Base.UIComponent'Class) return String; -- Get the locale that must be used to format the date. function Get_Locale (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; -- Create a date converter. function Create_Date_Converter (Date : in Style_Type; Time : in Style_Type; Format : in Format_Type; Locale : in String; Pattern : in String) return Date_Converter_Access; private type Date_Converter is new Converter with record Date_Style : Style_Type := DEFAULT; Time_Style : Style_Type := DEFAULT; Format : Format_Type; Locale : Util.Locales.Locale; Pattern : Ada.Strings.Unbounded.Unbounded_String; end record; end ASF.Converters.Dates;
----------------------------------------------------------------------- -- asf-converters-dates -- Date Converters -- Copyright (C) 2011, 2014, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Locales; with ASF.Components.Base; with ASF.Contexts.Faces; with ASF.Locales; -- The <b>ASF.Converters.Dates</b> defines the date converter to format a date object -- into a localized representation. -- -- See JSR 314 - JavaServer Faces Specification 9.4.3 <f:convertDateTime> -- (To_String is the JSF getAsString method and To_Object is the JSF getAsObject method) package ASF.Converters.Dates is type Style_Type is (DEFAULT, SHORT, MEDIUM, LONG, FULL); type Format_Type is (DATE, TIME, BOTH, CONVERTER_PATTERN, COMPONENT_FORMAT); -- ------------------------------ -- Converter -- ------------------------------ -- The <b>Date_Converter</b> translates the object value which holds an Ada.Calendar -- into a printable date representation. It translates a string into an Ada Calendar time. -- Unlike the Java implementation, the instance will be shared by multiple -- views and requests. type Date_Converter is new Converter with private; type Date_Converter_Access is access all Date_Converter'Class; -- Convert the object value into a string. The object value is associated -- with the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. function To_String (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in Util.Beans.Objects.Object) return String; -- Convert the date string into an object for the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. function To_Object (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in String) return Util.Beans.Objects.Object; -- Get the date format pattern that must be used for formatting a date on the given component. function Get_Pattern (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Bundle : in ASF.Locales.Bundle; Component : in ASF.Components.Base.UIComponent'Class) return String; -- Get the locale that must be used to format the date. function Get_Locale (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; -- Create a date converter. function Create_Date_Converter (Date : in Style_Type; Time : in Style_Type; Format : in Format_Type; Locale : in String; Pattern : in String) return Date_Converter_Access; private type Date_Converter is new Converter with record Date_Style : Style_Type := DEFAULT; Time_Style : Style_Type := DEFAULT; Format : Format_Type := BOTH; Locale : Util.Locales.Locale; Pattern : Ada.Strings.Unbounded.Unbounded_String; end record; end ASF.Converters.Dates;
Initialize the Date_Converter format member
Initialize the Date_Converter format member
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
51ce193fd59251ec8cc0f5599e2f2497a7cb9f5a
src/natools-web-simple_pages.adb
src/natools-web-simple_pages.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014-2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Simple_Pages; with Natools.Web.Error_Pages; with Natools.Web.Exchanges; with Natools.Web.Fallback_Render; package body Natools.Web.Simple_Pages is Expiration_Date_Key : constant S_Expressions.Atom := S_Expressions.To_Atom ("!expire"); Publication_Date_Key : constant S_Expressions.Atom := S_Expressions.To_Atom ("!publish"); procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom); function Comment_Path_Override (Template : in Page_Template) return S_Expressions.Atom_Refs.Immutable_Reference; procedure Execute (Data : in out Page_Data; Context : in Page_Template; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Read_Page is new S_Expressions.Interpreter_Loop (Page_Data, Page_Template, Execute); procedure Render_Page is new S_Expressions.Interpreter_Loop (Sites.Exchange, Page_Data, Render, Append); --------------------------- -- Page Data Constructor -- --------------------------- procedure Execute (Data : in out Page_Data; Context : in Page_Template; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is package Components renames Natools.Static_Maps.Web.Simple_Pages; begin case Components.To_Component (S_Expressions.To_String (Name)) is when Components.Error => Log (Severities.Error, "Unknown page component """ & S_Expressions.To_String (Name) & '"'); when Components.Comment_List => if Context.Comments.Is_Empty then Data.Comment_List.Set (Arguments); else declare Template : S_Expressions.Caches.Cursor := Context.Comments.Value; begin Data.Comment_List.Set (Template, Arguments, Comment_Path_Override (Context)); end; end if; when Components.Dates => Containers.Set_Dates (Data.Dates, Arguments); when Components.Elements => Containers.Add_Expressions (Data.Elements, Arguments); when Components.Maps => Data.Maps := String_Tables.Create (Arguments); when Components.Tags => Tags.Append (Data.Tags, Arguments); end case; end Execute; ------------------- -- Page Renderer -- ------------------- procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom) is pragma Unreferenced (Page); begin Exchange.Append (Data); end Append; procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class); procedure Render_Date (Log_Error : in Boolean); procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Page); end Re_Enter; procedure Render_Date (Log_Error : in Boolean) is begin if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Cursor : constant Containers.Date_Maps.Cursor := Page.Dates.Find (Arguments.Current_Atom); begin if not Containers.Date_Maps.Has_Element (Cursor) then if Log_Error then Log (Severities.Error, "Unable to find date """ & S_Expressions.To_String (Arguments.Current_Atom) & """ in page date map"); end if; return; end if; Arguments.Next; declare Item : constant Containers.Date := Containers.Date_Maps.Element (Cursor); begin S_Expressions.Templates.Dates.Render (Exchange, Arguments, Item.Time, Item.Offset); end; end; end if; end Render_Date; package Commands renames Natools.Static_Maps.Web.Simple_Pages; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown_Command => Fallback_Render (Exchange, Name, Arguments, "simple page", Re_Enter'Access, Page.Elements); when Commands.Comment_List => Comments.Render (Exchange, Page.Comment_List, Arguments); when Commands.Date => Render_Date (True); when Commands.My_Tags => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Prefix : constant S_Expressions.Atom := Arguments.Current_Atom; begin Arguments.Next; Tags.Render (Exchange, Page.Tags, Exchange.Site.Get_Tags, Prefix, Arguments); end; end if; when Commands.If_No_Date => if Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Page.Dates.Contains (Arguments.Current_Atom) then Arguments.Next; Render_Page (Arguments, Exchange, Page); end if; when Commands.Maps => String_Tables.Render (Exchange, Page.Maps, Arguments); when Commands.Optional_Date => Render_Date (False); when Commands.Path => Exchange.Append (Page.Web_Path.Query); when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments, Page.Tags); end case; end Render; ------------------------- -- Page_Data Interface -- ------------------------- not overriding procedure Get_Element (Data : in Page_Data; Name : in S_Expressions.Atom; Element : out S_Expressions.Caches.Cursor; Found : out Boolean) is Cursor : constant Containers.Expression_Maps.Cursor := Data.Elements.Find (Name); begin Found := Containers.Expression_Maps.Has_Element (Cursor); if Found then Element := Containers.Expression_Maps.Element (Cursor); end if; end Get_Element; ----------------------------- -- Page_Template Interface -- ----------------------------- function Comment_Path_Override (Template : in Page_Template) return S_Expressions.Atom_Refs.Immutable_Reference is use type S_Expressions.Atom; begin if Template.Comment_Path_Prefix.Is_Empty or else Template.Name.Is_Empty then return S_Expressions.Atom_Refs.Null_Immutable_Reference; else return S_Expressions.Atom_Ref_Constructors.Create (Template.Comment_Path_Prefix.Query & Template.Name.Query & (if Template.Comment_Path_Suffix.Is_Empty then S_Expressions.Null_Atom else Template.Comment_Path_Suffix.Query)); end if; end Comment_Path_Override; procedure Set_Comments (Object : in out Page_Template; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Object.Comments := (Is_Empty => False, Value => S_Expressions.Caches.Conditional_Move (Expression)); end Set_Comments; procedure Set_Comment_Path_Prefix (Object : in out Page_Template; Prefix : in S_Expressions.Atom) is begin if Prefix'Length > 0 then Object.Comment_Path_Prefix := S_Expressions.Atom_Ref_Constructors.Create (Prefix); else Object.Comment_Path_Prefix.Reset; end if; end Set_Comment_Path_Prefix; procedure Set_Comment_Path_Suffix (Object : in out Page_Template; Suffix : in S_Expressions.Atom) is begin if Suffix'Length > 0 then Object.Comment_Path_Suffix := S_Expressions.Atom_Ref_Constructors.Create (Suffix); else Object.Comment_Path_Suffix.Reset; end if; end Set_Comment_Path_Suffix; procedure Set_Elements (Object : in out Page_Template; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Containers.Set_Expressions (Object.Elements, Expression); end Set_Elements; ---------------------- -- Public Interface -- ---------------------- function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class; Template : in Page_Template := Default_Template; Name : in S_Expressions.Atom := S_Expressions.Null_Atom) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data; Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); Actual_Template : Page_Template := Template; begin Actual_Template.Name := (if Name'Length > 0 then S_Expressions.Atom_Ref_Constructors.Create (Name) else S_Expressions.Atom_Refs.Null_Immutable_Reference); Page.Self := Tags.Visible_Access (Page); Page.Elements := Template.Elements; Read_Page (Expression, Page.all, Actual_Template); return Result; end Create; function Create (File_Path, Web_Path : in S_Expressions.Atom_Refs.Immutable_Reference; Template : in Page_Template := Default_Template; Name : in S_Expressions.Atom := S_Expressions.Null_Atom) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data' (File_Path => File_Path, Web_Path => Web_Path, Elements => Template.Elements, Tags => <>, Self => null, Comment_List | Dates | Maps => <>); Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); Actual_Template : Page_Template := Template; begin Page.Self := Tags.Visible_Access (Page); Actual_Template.Name := (if Name'Length > 0 then S_Expressions.Atom_Ref_Constructors.Create (Name) else S_Expressions.Atom_Refs.Null_Immutable_Reference); Create_Page : declare Reader : Natools.S_Expressions.File_Readers.S_Reader := Natools.S_Expressions.File_Readers.Reader (S_Expressions.To_String (File_Path.Query)); begin Read_Page (Reader, Page.all, Actual_Template); end Create_Page; return Result; end Create; procedure Get_Lifetime (Page : in Page_Ref; Publication : out Ada.Calendar.Time; Has_Publication : out Boolean; Expiration : out Ada.Calendar.Time; Has_Expiration : out Boolean) is Accessor : constant Data_Refs.Accessor := Page.Ref.Query; Cursor : Containers.Date_Maps.Cursor; begin Cursor := Accessor.Dates.Find (Expiration_Date_Key); if Containers.Date_Maps.Has_Element (Cursor) then Has_Expiration := True; Expiration := Containers.Date_Maps.Element (Cursor).Time; else Has_Expiration := False; end if; Cursor := Accessor.Dates.Find (Publication_Date_Key); if Containers.Date_Maps.Has_Element (Cursor) then Has_Publication := True; Publication := Containers.Date_Maps.Element (Cursor).Time; else Has_Publication := False; end if; end Get_Lifetime; procedure Register (Page : in Page_Ref; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is begin Time_Check : declare use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Publication : Ada.Calendar.Time; Has_Publication : Boolean; Expiration : Ada.Calendar.Time; Has_Expiration : Boolean; begin Get_Lifetime (Page, Publication, Has_Publication, Expiration, Has_Expiration); if Has_Publication and then Publication >= Now then Sites.Expire_At (Builder, Publication); return; end if; if Has_Expiration then if Expiration < Now then return; else Sites.Expire_At (Builder, Expiration); end if; end if; end Time_Check; if Path'Length > 0 then Sites.Insert (Builder, Path, Page); end if; Sites.Insert (Builder, Page.Get_Tags, Page); Load_Comments : declare Mutator : constant Data_Refs.Mutator := Page.Ref.Update; begin Mutator.Comment_List.Load (Builder, Mutator.Self, Mutator.Web_Path); end Load_Comments; end Register; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Ref; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object.Ref.Query.Data.all); end Render; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Data; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object); end Render; overriding procedure Respond (Object : in out Page_Ref; Exchange : in out Sites.Exchange; Extra_Path : in S_Expressions.Atom) is use type S_Expressions.Offset; begin if Extra_Path'Length = 9 and then S_Expressions.To_String (Extra_Path) = "/comments" then Object.Ref.Update.Comment_List.Respond (Exchange, Extra_Path (Extra_Path'First + 9 .. Extra_Path'Last)); return; end if; if Extra_Path'Length > 0 then return; end if; declare Accessor : constant Data_Refs.Accessor := Object.Ref.Query; Expression : S_Expressions.Caches.Cursor; begin Check_Method : declare use Exchanges; Allowed : Boolean; begin Error_Pages.Check_Method (Exchange, (GET, HEAD), Allowed); if not Allowed then return; end if; end Check_Method; Expression := Exchange.Site.Get_Template (Accessor.Data.Elements, Expression, Exchange.Site.Default_Template, Lookup_Element => True, Lookup_Template => True, Lookup_Name => True); Render_Page (Expression, Exchange, Accessor.Data.all); end; end Respond; ----------------------- -- Page Constructors -- ----------------------- function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class is begin return Loader'(File_Path => S_Expressions.Atom_Ref_Constructors.Create (File)); end Create; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is Page : constant Page_Ref := Create (Object.File_Path, S_Expressions.Atom_Ref_Constructors.Create (Path)); begin Register (Page, Builder, Path); end Load; procedure Register_Loader (Site : in out Sites.Site) is begin Site.Register ("simple-page", Create'Access); end Register_Loader; end Natools.Web.Simple_Pages;
------------------------------------------------------------------------------ -- Copyright (c) 2014-2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Simple_Pages; with Natools.Web.Error_Pages; with Natools.Web.Exchanges; with Natools.Web.Fallback_Render; package body Natools.Web.Simple_Pages is Expiration_Date_Key : constant S_Expressions.Atom := S_Expressions.To_Atom ("!expire"); Publication_Date_Key : constant S_Expressions.Atom := S_Expressions.To_Atom ("!publish"); procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom); function Comment_Path_Override (Template : in Page_Template; Override : in S_Expressions.Lockable.Descriptor'Class) return S_Expressions.Atom_Refs.Immutable_Reference; procedure Execute (Data : in out Page_Data; Context : in Page_Template; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Read_Page is new S_Expressions.Interpreter_Loop (Page_Data, Page_Template, Execute); procedure Render_Page is new S_Expressions.Interpreter_Loop (Sites.Exchange, Page_Data, Render, Append); --------------------------- -- Page Data Constructor -- --------------------------- procedure Execute (Data : in out Page_Data; Context : in Page_Template; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is package Components renames Natools.Static_Maps.Web.Simple_Pages; begin case Components.To_Component (S_Expressions.To_String (Name)) is when Components.Error => Log (Severities.Error, "Unknown page component """ & S_Expressions.To_String (Name) & '"'); when Components.Comment_List => if Context.Comments.Is_Empty then Data.Comment_List.Set (Arguments); else declare Template : S_Expressions.Caches.Cursor := Context.Comments.Value; begin Data.Comment_List.Set (Template, Arguments, Comment_Path_Override (Context, Arguments)); end; end if; when Components.Dates => Containers.Set_Dates (Data.Dates, Arguments); when Components.Elements => Containers.Add_Expressions (Data.Elements, Arguments); when Components.Maps => Data.Maps := String_Tables.Create (Arguments); when Components.Tags => Tags.Append (Data.Tags, Arguments); end case; end Execute; ------------------- -- Page Renderer -- ------------------- procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom) is pragma Unreferenced (Page); begin Exchange.Append (Data); end Append; procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class); procedure Render_Date (Log_Error : in Boolean); procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Page); end Re_Enter; procedure Render_Date (Log_Error : in Boolean) is begin if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Cursor : constant Containers.Date_Maps.Cursor := Page.Dates.Find (Arguments.Current_Atom); begin if not Containers.Date_Maps.Has_Element (Cursor) then if Log_Error then Log (Severities.Error, "Unable to find date """ & S_Expressions.To_String (Arguments.Current_Atom) & """ in page date map"); end if; return; end if; Arguments.Next; declare Item : constant Containers.Date := Containers.Date_Maps.Element (Cursor); begin S_Expressions.Templates.Dates.Render (Exchange, Arguments, Item.Time, Item.Offset); end; end; end if; end Render_Date; package Commands renames Natools.Static_Maps.Web.Simple_Pages; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown_Command => Fallback_Render (Exchange, Name, Arguments, "simple page", Re_Enter'Access, Page.Elements); when Commands.Comment_List => Comments.Render (Exchange, Page.Comment_List, Arguments); when Commands.Date => Render_Date (True); when Commands.My_Tags => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Prefix : constant S_Expressions.Atom := Arguments.Current_Atom; begin Arguments.Next; Tags.Render (Exchange, Page.Tags, Exchange.Site.Get_Tags, Prefix, Arguments); end; end if; when Commands.If_No_Date => if Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Page.Dates.Contains (Arguments.Current_Atom) then Arguments.Next; Render_Page (Arguments, Exchange, Page); end if; when Commands.Maps => String_Tables.Render (Exchange, Page.Maps, Arguments); when Commands.Optional_Date => Render_Date (False); when Commands.Path => Exchange.Append (Page.Web_Path.Query); when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments, Page.Tags); end case; end Render; ------------------------- -- Page_Data Interface -- ------------------------- not overriding procedure Get_Element (Data : in Page_Data; Name : in S_Expressions.Atom; Element : out S_Expressions.Caches.Cursor; Found : out Boolean) is Cursor : constant Containers.Expression_Maps.Cursor := Data.Elements.Find (Name); begin Found := Containers.Expression_Maps.Has_Element (Cursor); if Found then Element := Containers.Expression_Maps.Element (Cursor); end if; end Get_Element; ----------------------------- -- Page_Template Interface -- ----------------------------- function Comment_Path_Override (Template : in Page_Template; Override : in S_Expressions.Lockable.Descriptor'Class) return S_Expressions.Atom_Refs.Immutable_Reference is use type S_Expressions.Atom; use type S_Expressions.Events.Event; Name_Override : constant Boolean := Override.Current_Event = S_Expressions.Events.Add_Atom; Name : constant S_Expressions.Atom := (if Name_Override then Override.Current_Atom elsif not Template.Name.Is_Empty then Template.Name.Query else S_Expressions.Null_Atom); begin if Template.Comment_Path_Prefix.Is_Empty or else (not Name_Override and then Template.Name.Is_Empty) then return S_Expressions.Atom_Refs.Null_Immutable_Reference; else return S_Expressions.Atom_Ref_Constructors.Create (Template.Comment_Path_Prefix.Query & Name & (if Template.Comment_Path_Suffix.Is_Empty then S_Expressions.Null_Atom else Template.Comment_Path_Suffix.Query)); end if; end Comment_Path_Override; procedure Set_Comments (Object : in out Page_Template; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Object.Comments := (Is_Empty => False, Value => S_Expressions.Caches.Conditional_Move (Expression)); end Set_Comments; procedure Set_Comment_Path_Prefix (Object : in out Page_Template; Prefix : in S_Expressions.Atom) is begin if Prefix'Length > 0 then Object.Comment_Path_Prefix := S_Expressions.Atom_Ref_Constructors.Create (Prefix); else Object.Comment_Path_Prefix.Reset; end if; end Set_Comment_Path_Prefix; procedure Set_Comment_Path_Suffix (Object : in out Page_Template; Suffix : in S_Expressions.Atom) is begin if Suffix'Length > 0 then Object.Comment_Path_Suffix := S_Expressions.Atom_Ref_Constructors.Create (Suffix); else Object.Comment_Path_Suffix.Reset; end if; end Set_Comment_Path_Suffix; procedure Set_Elements (Object : in out Page_Template; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Containers.Set_Expressions (Object.Elements, Expression); end Set_Elements; ---------------------- -- Public Interface -- ---------------------- function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class; Template : in Page_Template := Default_Template; Name : in S_Expressions.Atom := S_Expressions.Null_Atom) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data; Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); Actual_Template : Page_Template := Template; begin Actual_Template.Name := (if Name'Length > 0 then S_Expressions.Atom_Ref_Constructors.Create (Name) else S_Expressions.Atom_Refs.Null_Immutable_Reference); Page.Self := Tags.Visible_Access (Page); Page.Elements := Template.Elements; Read_Page (Expression, Page.all, Actual_Template); return Result; end Create; function Create (File_Path, Web_Path : in S_Expressions.Atom_Refs.Immutable_Reference; Template : in Page_Template := Default_Template; Name : in S_Expressions.Atom := S_Expressions.Null_Atom) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data' (File_Path => File_Path, Web_Path => Web_Path, Elements => Template.Elements, Tags => <>, Self => null, Comment_List | Dates | Maps => <>); Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); Actual_Template : Page_Template := Template; begin Page.Self := Tags.Visible_Access (Page); Actual_Template.Name := (if Name'Length > 0 then S_Expressions.Atom_Ref_Constructors.Create (Name) else S_Expressions.Atom_Refs.Null_Immutable_Reference); Create_Page : declare Reader : Natools.S_Expressions.File_Readers.S_Reader := Natools.S_Expressions.File_Readers.Reader (S_Expressions.To_String (File_Path.Query)); begin Read_Page (Reader, Page.all, Actual_Template); end Create_Page; return Result; end Create; procedure Get_Lifetime (Page : in Page_Ref; Publication : out Ada.Calendar.Time; Has_Publication : out Boolean; Expiration : out Ada.Calendar.Time; Has_Expiration : out Boolean) is Accessor : constant Data_Refs.Accessor := Page.Ref.Query; Cursor : Containers.Date_Maps.Cursor; begin Cursor := Accessor.Dates.Find (Expiration_Date_Key); if Containers.Date_Maps.Has_Element (Cursor) then Has_Expiration := True; Expiration := Containers.Date_Maps.Element (Cursor).Time; else Has_Expiration := False; end if; Cursor := Accessor.Dates.Find (Publication_Date_Key); if Containers.Date_Maps.Has_Element (Cursor) then Has_Publication := True; Publication := Containers.Date_Maps.Element (Cursor).Time; else Has_Publication := False; end if; end Get_Lifetime; procedure Register (Page : in Page_Ref; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is begin Time_Check : declare use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Publication : Ada.Calendar.Time; Has_Publication : Boolean; Expiration : Ada.Calendar.Time; Has_Expiration : Boolean; begin Get_Lifetime (Page, Publication, Has_Publication, Expiration, Has_Expiration); if Has_Publication and then Publication >= Now then Sites.Expire_At (Builder, Publication); return; end if; if Has_Expiration then if Expiration < Now then return; else Sites.Expire_At (Builder, Expiration); end if; end if; end Time_Check; if Path'Length > 0 then Sites.Insert (Builder, Path, Page); end if; Sites.Insert (Builder, Page.Get_Tags, Page); Load_Comments : declare Mutator : constant Data_Refs.Mutator := Page.Ref.Update; begin Mutator.Comment_List.Load (Builder, Mutator.Self, Mutator.Web_Path); end Load_Comments; end Register; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Ref; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object.Ref.Query.Data.all); end Render; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Data; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object); end Render; overriding procedure Respond (Object : in out Page_Ref; Exchange : in out Sites.Exchange; Extra_Path : in S_Expressions.Atom) is use type S_Expressions.Offset; begin if Extra_Path'Length = 9 and then S_Expressions.To_String (Extra_Path) = "/comments" then Object.Ref.Update.Comment_List.Respond (Exchange, Extra_Path (Extra_Path'First + 9 .. Extra_Path'Last)); return; end if; if Extra_Path'Length > 0 then return; end if; declare Accessor : constant Data_Refs.Accessor := Object.Ref.Query; Expression : S_Expressions.Caches.Cursor; begin Check_Method : declare use Exchanges; Allowed : Boolean; begin Error_Pages.Check_Method (Exchange, (GET, HEAD), Allowed); if not Allowed then return; end if; end Check_Method; Expression := Exchange.Site.Get_Template (Accessor.Data.Elements, Expression, Exchange.Site.Default_Template, Lookup_Element => True, Lookup_Template => True, Lookup_Name => True); Render_Page (Expression, Exchange, Accessor.Data.all); end; end Respond; ----------------------- -- Page Constructors -- ----------------------- function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class is begin return Loader'(File_Path => S_Expressions.Atom_Ref_Constructors.Create (File)); end Create; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is Page : constant Page_Ref := Create (Object.File_Path, S_Expressions.Atom_Ref_Constructors.Create (Path)); begin Register (Page, Builder, Path); end Load; procedure Register_Loader (Site : in out Sites.Site) is begin Site.Register ("simple-page", Create'Access); end Register_Loader; end Natools.Web.Simple_Pages;
add support for comment name override in templated paths
simple_pages: add support for comment name override in templated paths
Ada
isc
faelys/natools-web,faelys/natools-web
603b834bdc748b261e29f9e7a532da8136700312
samples/evaluate.adb
samples/evaluate.adb
----------------------------------------------------------------------- -- el -- Evaluate an EL expression -- 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 EL.Expressions; with EL.Objects; with EL.Contexts.Default; with Ada.Text_IO; procedure Evaluate is Ctx : EL.Contexts.Default.Default_Context; E : EL.Expressions.Expression; Result : EL.Objects.Object; begin E := EL.Expressions.Create_Expression ("#{1 + (2 - 3) * 4}", Ctx); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("Result: " & EL.Objects.To_String (Result)); end Evaluate;
----------------------------------------------------------------------- -- el -- Evaluate an EL expression -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Objects; with EL.Contexts.Default; with Ada.Text_IO; procedure Evaluate is Expr : constant String := "#{1 + (2 - 3) * 4}"; Ctx : EL.Contexts.Default.Default_Context; E : EL.Expressions.Expression; Result : EL.Objects.Object; begin Ada.Text_IO.Put_Line ("Evaluate: " & Expr); E := EL.Expressions.Create_Expression (Expr, Ctx); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("Result: " & EL.Objects.To_String (Result)); end Evaluate;
Print the expression being evaluated
Print the expression being evaluated
Ada
apache-2.0
stcarrez/ada-el
42437a3b8f64d4abab25762eafb3f7c78c2546aa
src/gen-commands-project.adb
src/gen-commands-project.adb
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- 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.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -web -tool -ado") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Gen.Commands.Usage; return; end if; if Util.Strings.Index (Arg2, '@') > Arg2'First then Generator.Set_Project_Property ("author_email", Arg2); if Arg3'Length = 0 then Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2)); else Generator.Set_Project_Property ("author", Arg3); end if; elsif Util.Strings.Index (Arg3, '@') > Arg3'First then Generator.Set_Project_Property ("author", Arg2); Generator.Set_Project_Property ("author_email", Arg3); elsif Arg3'Length > 0 then Generator.Error ("The last argument should be the author's email address."); Gen.Commands.Usage; return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); end if; end if; end; end; 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); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|proprietary] [--web] [--tool] [--ado] " & "NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the GNU license or"); Put_Line (" a proprietary license. The author's name and email addresses"); Put_Line (" are also reported in generated files."); New_Line; Put_Line (" --web Generate a Web application (the default)"); Put_Line (" --tool Generate a command line tool"); Put_Line (" --ado Generate a database tool operation for ADO"); end Help; end Gen.Commands.Project;
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; Gtk_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -web -tool -ado -gtk") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; elsif Full_Switch = "-gtk" then Gtk_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Gen.Commands.Usage; return; end if; if Util.Strings.Index (Arg2, '@') > Arg2'First then Generator.Set_Project_Property ("author_email", Arg2); if Arg3'Length = 0 then Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2)); else Generator.Set_Project_Property ("author", Arg3); end if; elsif Util.Strings.Index (Arg3, '@') > Arg3'First then Generator.Set_Project_Property ("author", Arg2); Generator.Set_Project_Property ("author_email", Arg3); elsif Arg3'Length > 0 then Generator.Error ("The last argument should be the author's email address."); Gen.Commands.Usage; return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); elsif Gtk_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); end if; end if; end; end; 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); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|proprietary] [--web] [--tool] [--ado] " & "[--gtk] NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the GNU license or"); Put_Line (" a proprietary license. The author's name and email addresses"); Put_Line (" are also reported in generated files."); New_Line; Put_Line (" --web Generate a Web application (the default)"); Put_Line (" --tool Generate a command line tool"); Put_Line (" --ado Generate a database tool operation for ADO"); Put_Line (" --gtk Generate a GtkAda project"); end Help; end Gen.Commands.Project;
Add option --gtk to create a Gtk Ada application
Add option --gtk to create a Gtk Ada application
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
2ec50bd94ace8ad98c94948e24d7f5b2c25d478e
ARM/Nordic/drivers/nrf51-gpio.adb
ARM/Nordic/drivers/nrf51-gpio.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 NRF51_SVD.GPIO; use NRF51_SVD.GPIO; package body nRF51.GPIO is --------- -- Set -- --------- overriding function Set (This : GPIO_Point) return Boolean is begin return GPIO_Periph.OUT_k.Arr (This.Pin) = High; end Set; --------- -- Set -- --------- overriding procedure Set (This : in out GPIO_Point) is begin GPIO_Periph.OUTSET.Arr (This.Pin) := Set; end Set; ----------- -- Clear -- ----------- overriding procedure Clear (This : in out GPIO_Point) is begin GPIO_Periph.OUTCLR.Arr (This.Pin) := Clear; end Clear; ------------ -- Toggle -- ------------ overriding procedure Toggle (This : in out GPIO_Point) is begin if This.Set then This.Clear; else This.Set; end if; end Toggle; ------------------ -- Configure_IO -- ------------------ procedure Configure_IO (This : GPIO_Point; Config : GPIO_Configuration) is CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin); begin CNF.DIR := (case Config.Mode is when Mode_In => Input, when Mode_Out => Output); CNF.INPUT := (case Config.Input_Buffer is when Input_Buffer_Connect => Connect, when Input_Buffer_Disconnect => Disconnect); CNF.PULL := (case Config.Resistors is when No_Pull => Disabled, when Pull_Up => Pullup, when Pull_Down => Pulldown); CNF.DRIVE := (case Config.Drive is when Drive_S0S1 => S0S1, when Drive_H0S1 => H0S1, when Drive_S0H1 => S0H1, when Drive_H0H1 => H0H1, when Drive_D0S1 => D0S1, when Drive_D0H1 => D0H1, when Drive_S0D1 => S0D1, when Drive_H0D1 => H0D1); CNF.SENSE := (case Config.Sense is when Sense_Disabled => Disabled, when Sense_For_High_Level => High, when Sense_For_Low_Level => Low); end Configure_IO; end nRF51.GPIO;
------------------------------------------------------------------------------ -- -- -- 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 NRF51_SVD.GPIO; use NRF51_SVD.GPIO; package body nRF51.GPIO is --------- -- Set -- --------- overriding function Set (This : GPIO_Point) return Boolean is begin return GPIO_Periph.OUT_k.Arr (This.Pin) = High; end Set; --------- -- Set -- --------- overriding procedure Set (This : in out GPIO_Point) is begin GPIO_Periph.OUT_k.Arr (This.Pin) := High; end Set; ----------- -- Clear -- ----------- overriding procedure Clear (This : in out GPIO_Point) is begin GPIO_Periph.OUT_k.Arr (This.Pin) := Low; end Clear; ------------ -- Toggle -- ------------ overriding procedure Toggle (This : in out GPIO_Point) is begin if This.Set then This.Clear; else This.Set; end if; end Toggle; ------------------ -- Configure_IO -- ------------------ procedure Configure_IO (This : GPIO_Point; Config : GPIO_Configuration) is CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin); begin CNF.DIR := (case Config.Mode is when Mode_In => Input, when Mode_Out => Output); CNF.INPUT := (case Config.Input_Buffer is when Input_Buffer_Connect => Connect, when Input_Buffer_Disconnect => Disconnect); CNF.PULL := (case Config.Resistors is when No_Pull => Disabled, when Pull_Up => Pullup, when Pull_Down => Pulldown); CNF.DRIVE := (case Config.Drive is when Drive_S0S1 => S0S1, when Drive_H0S1 => H0S1, when Drive_S0H1 => S0H1, when Drive_H0H1 => H0H1, when Drive_D0S1 => D0S1, when Drive_D0H1 => D0H1, when Drive_S0D1 => S0D1, when Drive_H0D1 => H0D1); CNF.SENSE := (case Config.Sense is when Sense_Disabled => Disabled, when Sense_For_High_Level => High, when Sense_For_Low_Level => Low); end Configure_IO; end nRF51.GPIO;
Fix GPIO Set and Clear
nRF51: Fix GPIO Set and Clear
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
002d23007da091825a6d2aaa12d5540a0cdd23d7
awa/plugins/awa-questions/regtests/awa-questions-modules-tests.adb
awa/plugins/awa-questions/regtests/awa-questions-modules-tests.adb
----------------------------------------------------------------------- -- awa-questions-modules-tests -- Unit tests for storage service -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with ASF.Contexts.Faces; with ASF.Contexts.Faces.Mockup; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Questions.Modules; with AWA.Questions.Beans; with AWA.Votes.Beans; with AWA.Tests.Helpers.Users; package body AWA.Questions.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Questions.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Services.Delete_Question", Test_Delete_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list", Test_List_Questions'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean", Test_Question_Vote'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)", Test_Question_Vote'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Module; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I append strings in Ada?"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do?"); T.Manager.Save_Question (Q); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do? " & "This is a stupid question for someone who reads this file. " & "But I need some long text for the unit test."); T.Manager.Save_Question (Q); end Test_Create_Question; -- ------------------------------ -- Test deletion of a question. -- ------------------------------ procedure Test_Delete_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Module; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I search strings in Ada?"); Q.Set_Description ("I have two strings that I want to search. % does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); T.Manager.Delete_Question (Q); end Test_Delete_Question; -- ------------------------------ -- Test list of questions. -- ------------------------------ procedure Test_List_Questions (T : in out Test) is use AWA.Questions.Models; use type Util.Beans.Basic.Readonly_Bean_Access; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Module : AWA.Questions.Modules.Question_Module_Access; List : Util.Beans.Basic.Readonly_Bean_Access; Bean : Util.Beans.Objects.Object; Count : Natural; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Module := AWA.Questions.Modules.Get_Question_Module; List := AWA.Questions.Beans.Create_Question_List_Bean (Module); T.Assert (List /= null, "The Create_Question_List_Bean returned null"); Bean := Util.Beans.Objects.To_Object (List); T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null"); Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count; T.Assert (Count > 0, "The list of question is empty"); end Test_List_Questions; -- ------------------------------ -- Do a vote on a question through the question vote bean. -- ------------------------------ procedure Do_Vote (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context; Outcome : Ada.Strings.Unbounded.Unbounded_String; Bean : Util.Beans.Basic.Readonly_Bean_Access; Vote : AWA.Votes.Beans.Vote_Bean_Access; begin Context.Set_Parameter ("id", "1"); Bean := Context.Get_Bean ("questionVote"); T.Assert (Bean /= null, "The questionVote bean was not created"); T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class, "The questionVote is not a Vote_Bean"); Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access; Vote.Rating := 1; Vote.Entity_Id := 1; Vote.Vote_Up (Outcome); end Do_Vote; -- ------------------------------ -- Test anonymous user voting for a question. -- ------------------------------ procedure Test_Question_Vote_Anonymous (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Do_Vote (T); T.Fail ("Anonymous users should not be allowed to vote"); exception when AWA.Permissions.NO_PERMISSION => null; end Test_Question_Vote_Anonymous; -- ------------------------------ -- Test voting for a question. -- ------------------------------ procedure Test_Question_Vote (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Do_Vote (T); end Test_Question_Vote; end AWA.Questions.Modules.Tests;
----------------------------------------------------------------------- -- awa-questions-modules-tests -- Unit tests for storage service -- Copyright (C) 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with ASF.Contexts.Faces; with ASF.Contexts.Faces.Mockup; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Questions.Modules; with AWA.Questions.Beans; with AWA.Votes.Beans; with AWA.Tests.Helpers.Users; package body AWA.Questions.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Questions.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Services.Delete_Question", Test_Delete_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list", Test_List_Questions'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean", Test_Question_Vote'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)", Test_Question_Vote'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Module; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I append strings in Ada?"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do?"); T.Manager.Save_Question (Q); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do? " & "This is a stupid question for someone who reads this file. " & "But I need some long text for the unit test."); T.Manager.Save_Question (Q); end Test_Create_Question; -- ------------------------------ -- Test deletion of a question. -- ------------------------------ procedure Test_Delete_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Module; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I search strings in Ada?"); Q.Set_Description ("I have two strings that I want to search. % does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); T.Manager.Delete_Question (Q); end Test_Delete_Question; -- ------------------------------ -- Test list of questions. -- ------------------------------ procedure Test_List_Questions (T : in out Test) is use AWA.Questions.Models; use AWA.Questions.Beans; use type Util.Beans.Basic.Readonly_Bean_Access; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Module : AWA.Questions.Modules.Question_Module_Access; List : Util.Beans.Basic.Readonly_Bean_Access; Bean : Util.Beans.Objects.Object; Count : Natural; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Module := AWA.Questions.Modules.Get_Question_Module; List := AWA.Questions.Beans.Create_Question_List_Bean (Module); T.Assert (List /= null, "The Create_Question_List_Bean returned null"); Bean := Util.Beans.Objects.To_Object (List); T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null"); T.Assert (List.all in Questions.Beans.Question_List_Bean'Class, "The Create_Question_List_Bean returns an invalid bean"); Count := Questions.Beans.Question_List_Bean'Class (List.all).Questions.Get_Count; T.Assert (Count > 0, "The list of question is empty"); end Test_List_Questions; -- ------------------------------ -- Do a vote on a question through the question vote bean. -- ------------------------------ procedure Do_Vote (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context; Outcome : Ada.Strings.Unbounded.Unbounded_String; Bean : Util.Beans.Basic.Readonly_Bean_Access; Vote : AWA.Votes.Beans.Vote_Bean_Access; begin Context.Set_Parameter ("id", "1"); Bean := Context.Get_Bean ("questionVote"); T.Assert (Bean /= null, "The questionVote bean was not created"); T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class, "The questionVote is not a Vote_Bean"); Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access; Vote.Rating := 1; Vote.Entity_Id := 1; Vote.Vote_Up (Outcome); end Do_Vote; -- ------------------------------ -- Test anonymous user voting for a question. -- ------------------------------ procedure Test_Question_Vote_Anonymous (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Do_Vote (T); T.Fail ("Anonymous users should not be allowed to vote"); exception when AWA.Permissions.NO_PERMISSION => null; end Test_Question_Vote_Anonymous; -- ------------------------------ -- Test voting for a question. -- ------------------------------ procedure Test_Question_Vote (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Do_Vote (T); end Test_Question_Vote; end AWA.Questions.Modules.Tests;
Fix the unit test after changes in the bean definitions
Fix the unit test after changes in the bean definitions
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
97bd860f9cc402fdfedac92370b1e5deee46b92e
src/util-listeners-lifecycles.ads
src/util-listeners-lifecycles.ads
----------------------------------------------------------------------- -- util-listeners-lifecycles -- Listeners -- 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. ----------------------------------------------------------------------- -- The `Lifecycles` package provides a listener interface dedicated to -- track lifecycle managements on objects. It defines a set of procedures to be -- notified when an object is created, updated or deleted. generic type Element_Type (<>) is limited private; package Util.Listeners.Lifecycles is -- ------------------------------ -- Lifecycle listener -- ------------------------------ type Listener is limited interface and Util.Listeners.Listener; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. procedure On_Create (Instance : in Listener; Item : in Element_Type) is abstract; -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. procedure On_Update (Instance : in Listener; Item : in Element_Type) is abstract; -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. procedure On_Delete (Instance : in Listener; Item : in Element_Type) is abstract; -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been created (calls `On_Create`). procedure Notify_Create (List : in Util.Listeners.List; Item : in Element_Type); -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been updated (calls `On_Update`). procedure Notify_Update (List : in Util.Listeners.List; Item : in Element_Type); -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been deleted (calls `On_Delete`). procedure Notify_Delete (List : in Util.Listeners.List; Item : in Element_Type); end Util.Listeners.Lifecycles;
----------------------------------------------------------------------- -- util-listeners-lifecycles -- Listeners -- 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. ----------------------------------------------------------------------- -- The `Lifecycles` package provides a listener interface dedicated to -- track lifecycle managements on objects. It defines a set of procedures to be -- notified when an object is created, updated or deleted. -- -- Notes: another implementation can be made by using three different listener lists -- that use the simple observer pattern. generic type Element_Type (<>) is limited private; package Util.Listeners.Lifecycles is -- ------------------------------ -- Lifecycle listener -- ------------------------------ type Listener is limited interface and Util.Listeners.Listener; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. procedure On_Create (Instance : in Listener; Item : in Element_Type) is abstract; -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. procedure On_Update (Instance : in Listener; Item : in Element_Type) is abstract; -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. procedure On_Delete (Instance : in Listener; Item : in Element_Type) is abstract; -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been created (calls `On_Create`). procedure Notify_Create (List : in Util.Listeners.List; Item : in Element_Type); -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been updated (calls `On_Update`). procedure Notify_Update (List : in Util.Listeners.List; Item : in Element_Type); -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been deleted (calls `On_Delete`). procedure Notify_Delete (List : in Util.Listeners.List; Item : in Element_Type); end Util.Listeners.Lifecycles;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7836103e0b33a45b61c0c7d4cb51ea9dd1125cb4
awa/src/awa-permissions-beans.adb
awa/src/awa-permissions-beans.adb
----------------------------------------------------------------------- -- awa-permissions-beans -- Permission beans -- 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 ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with AWA.Services.Contexts; with AWA.Events.Action_Method; with AWA.Permissions.Services; package body AWA.Permissions.Beans is use Ada.Strings.Unbounded; package ASC renames AWA.Services.Contexts; package Create_Binding is new AWA.Events.Action_Method.Bind (Bean => Permission_Bean, Method => Create, Name => "create"); Permission_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Binding.Proxy'Access); -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Permission_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_id" then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_type" then From.Kind := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Permission_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Permission_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new permission. -- ------------------------------ procedure Create (Bean : in out Permission_Bean; Event : in AWA.Events.Module_Event'Class) is Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; begin Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, To_String (Bean.Kind)); AWA.Permissions.Services.Add_Permission (Session => DB, Entity => Bean.Get_Entity_Id, Kind => Kind, User => Ctx.Get_User_Identifier); Ctx.Commit; end Create; -- ------------------------------ -- Create the permission bean instance. -- ------------------------------ function Create_Permission_Bean return Util.Beans.Basic.Readonly_Bean_Access is begin return new Permission_Bean; end Create_Permission_Bean; end AWA.Permissions.Beans;
----------------------------------------------------------------------- -- awa-permissions-beans -- Permission beans -- 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 ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with AWA.Services.Contexts; with AWA.Events.Action_Method; with AWA.Permissions.Services; package body AWA.Permissions.Beans is use Ada.Strings.Unbounded; package ASC renames AWA.Services.Contexts; package Create_Binding is new AWA.Events.Action_Method.Bind (Bean => Permission_Bean, Method => Create, Name => "create"); Permission_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Binding.Proxy'Access); -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Permission_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_id" then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_type" then From.Kind := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Permission_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Permission_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new permission. -- ------------------------------ procedure Create (Bean : in out Permission_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Event); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; begin Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, To_String (Bean.Kind)); AWA.Permissions.Services.Add_Permission (Session => DB, Entity => Bean.Get_Entity_Id, Kind => Kind, User => Ctx.Get_User_Identifier); Ctx.Commit; end Create; -- ------------------------------ -- Create the permission bean instance. -- ------------------------------ function Create_Permission_Bean return Util.Beans.Basic.Readonly_Bean_Access is begin return new Permission_Bean; end Create_Permission_Bean; end AWA.Permissions.Beans;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
89aaff3b57932b904d8f27c514facdebd3f0751a
src/el-utils.ads
src/el-utils.ads
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with Util.Beans.Objects; with EL.Contexts; package EL.Utils is -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class); -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String; -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object; -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object; end EL.Utils;
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- Copyright (C) 2011, 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with Util.Beans.Objects; with EL.Contexts; package EL.Utils is -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class); procedure Expand (Config : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class); -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String; -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object; -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object; end EL.Utils;
Add Expand procedure to expand the properties in place (small optimization)
Add Expand procedure to expand the properties in place (small optimization)
Ada
apache-2.0
stcarrez/ada-el
bbdd40ec3013b92e93e6daea8d618f01d5d06597
src/dw1000-bsp.ads
src/dw1000-bsp.ads
------------------------------------------------------------------------------- -- Copyright (c) 2016 Daniel King -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- with DW1000.Types; -- This package defines low-level procedures for interfacing with the DW1000 -- at the physical layer. -- -- The body for this package is not included in this project as it is very -- specific to the target hardware. Therefore, the body for this package -- must be implemented by the user for their target board. package DW1000.BSP with SPARK_Mode => On, Abstract_State => (Device_State with External), Initializes => Device_State is procedure Reset_DW1000 with Global => (Output => Device_State), Depends => (Device_State => null); -- Resets the DW1000 via the RSTn line. procedure Acknowledge_DW1000_IRQ with Global => (In_Out => Device_State); -- Acknowledge the IRQ request from the DW1000. -- -- This should be called from the interrupt handler of the DW1000 IRQ line -- to acknowledge the interrupt. -- --- Failure to call this procedure from the interrupt handler may result in -- an infinite interrupt loop. procedure Disable_DW1000_IRQ with Global => (In_Out => Device_State); -- Disables the DW1000 IRQ to prevent the DW1000 interrupt from being -- triggered. -- -- Any IRQs requested after calling this function should be held pending -- until Enable_DW1000_IRQ is called. procedure Enable_DW1000_IRQ with Global => (In_Out => Device_State); -- Enables the DW1000 IRQ. procedure Use_Slow_SPI_Clock; -- Switch the BSP to use a slow SPI clock speed (no faster than 3 MHz). -- -- The slow SPI clock speed should be used when the DW1000 is in the INIT -- state. procedure Use_Fast_SPI_Clock; -- Switch the BSP to use a faster SPI clock speed (no faster than 20 MHz). -- -- The fast SPI clock speed can be used when the DW1000 has left the INIT -- state. procedure Write_Transaction(Header : in DW1000.Types.Byte_Array; Data : in DW1000.Types.Byte_Array) with Global => (In_Out => Device_State), Depends => (Device_State => + (Header, Data)), Pre => (Header'Length in 1 .. 3 and Data'Length > 0); -- Perform a "write" transaction to the DW1000. -- -- This procedure executes a write transaction by performing the following -- steps:z -- 1. Select the DW1000 on the SPI bus. -- 2. Send the transaction header bytes (1 .. 3 bytes) via the SPI -- interface. -- 3. Send the transaction data (variable length) to the DW1000 via the -- SPI interface. -- 4. Deselect the DW1000 on the SPI bus. -- -- Note: This procedure must not block. I.e. the procedure must not use -- the 'delay until' statement, nor call any protected entries. procedure Read_Transaction(Header : in DW1000.Types.Byte_Array; Data : out DW1000.Types.Byte_Array) with Global => (In_Out => Device_State), Depends => (Device_State => + (Header, Data), Data => (Header, Device_State)), Pre => (Header'Length in 1 .. 3 and Data'Length > 0); -- Perform a "read" transaction from the DW1000. -- -- This procedure executes a write transaction by performing the following -- steps: -- 1. Select the DW1000 on the SPI bus. -- 2. Send the transaction header bytes (1 .. 3 bytes) via the SPI -- interface. -- 3. Read the transaction data (variable length) from the DW1000 via -- the SPI interface, and write the received bytes to the 'Data' byte -- array. -- 4. Deselect the DW1000 on the SPI bus. -- -- Note: This procedure must not block. I.e. the procedure must not use -- the 'delay until' statement, nor call any protected entries. end DW1000.BSP;
------------------------------------------------------------------------------- -- Copyright (c) 2016 Daniel King -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- with DW1000.Types; -- This package defines low-level procedures for interfacing with the DW1000 -- at the physical layer. -- -- The body for this package is not included in this project as it is very -- specific to the target hardware. Therefore, the body for this package -- must be implemented by the user for their target board. package DW1000.BSP with SPARK_Mode => On, Abstract_State => (Device_State with External), Initializes => Device_State is procedure Reset_DW1000 with Global => (Output => Device_State), Depends => (Device_State => null); -- Resets the DW1000 via the RSTn line. procedure Acknowledge_DW1000_IRQ with Global => (In_Out => Device_State); -- Acknowledge the IRQ request from the DW1000. -- -- This should be called from the interrupt handler of the DW1000 IRQ line -- to acknowledge the interrupt. -- --- Failure to call this procedure from the interrupt handler may result in -- an infinite interrupt loop. procedure Disable_DW1000_IRQ with Global => (In_Out => Device_State); -- Disables the DW1000 IRQ to prevent the DW1000 interrupt from being -- triggered. -- -- Any IRQs requested after calling this function should be held pending -- until Enable_DW1000_IRQ is called. procedure Enable_DW1000_IRQ with Global => (In_Out => Device_State); -- Enables the DW1000 IRQ. procedure Use_Slow_SPI_Clock with Global => (In_Out => Device_State); -- Switch the BSP to use a slow SPI clock speed (no faster than 3 MHz). -- -- The slow SPI clock speed should be used when the DW1000 is in the INIT -- state. procedure Use_Fast_SPI_Clock with Global => (In_Out => Device_State); -- Switch the BSP to use a faster SPI clock speed (no faster than 20 MHz). -- -- The fast SPI clock speed can be used when the DW1000 has left the INIT -- state. procedure Write_Transaction(Header : in DW1000.Types.Byte_Array; Data : in DW1000.Types.Byte_Array) with Global => (In_Out => Device_State), Depends => (Device_State => + (Header, Data)), Pre => (Header'Length in 1 .. 3 and Data'Length > 0); -- Perform a "write" transaction to the DW1000. -- -- This procedure executes a write transaction by performing the following -- steps:z -- 1. Select the DW1000 on the SPI bus. -- 2. Send the transaction header bytes (1 .. 3 bytes) via the SPI -- interface. -- 3. Send the transaction data (variable length) to the DW1000 via the -- SPI interface. -- 4. Deselect the DW1000 on the SPI bus. -- -- Note: This procedure must not block. I.e. the procedure must not use -- the 'delay until' statement, nor call any protected entries. procedure Read_Transaction(Header : in DW1000.Types.Byte_Array; Data : out DW1000.Types.Byte_Array) with Global => (In_Out => Device_State), Depends => (Device_State => + (Header, Data), Data => (Header, Device_State)), Pre => (Header'Length in 1 .. 3 and Data'Length > 0); -- Perform a "read" transaction from the DW1000. -- -- This procedure executes a write transaction by performing the following -- steps: -- 1. Select the DW1000 on the SPI bus. -- 2. Send the transaction header bytes (1 .. 3 bytes) via the SPI -- interface. -- 3. Read the transaction data (variable length) from the DW1000 via -- the SPI interface, and write the received bytes to the 'Data' byte -- array. -- 4. Deselect the DW1000 on the SPI bus. -- -- Note: This procedure must not block. I.e. the procedure must not use -- the 'delay until' statement, nor call any protected entries. end DW1000.BSP;
Add globals annotation to new BSP procedures
Add globals annotation to new BSP procedures
Ada
mit
damaki/DW1000
2ddb05fbd4235dea42c353aaaf19adbf729565a0
src/asf-components-html-text.adb
src/asf-components-html-text.adb
----------------------------------------------------------------------- -- html -- ASF HTML Components -- 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 EL.Objects; with ASF.Components.Core; with Util.Strings; 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 value to write on the output. -- ------------------------------ function Get_Value (UI : in UIOutput) return EL.Objects.Object is begin return UI.Get_Attribute (UI.Get_Context.all, "value"); -- return UI.Value; end Get_Value; -- ------------------------------ -- Set the value to write on the output. -- ------------------------------ procedure Set_Value (UI : in out UIOutput; Value : in EL.Objects.Object) is begin UI.Value := Value; end Set_Value; procedure Write_Output (UI : in UIOutput; Context : in out Faces_Context'Class; Value : in EL.Objects.Object) is Writer : constant ResponseWriter_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_Text (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 => UI.Get_Value); end if; end Encode_Begin; procedure Encode_Begin (UI : in UILabel; Context : in out Faces_Context'Class) is Writer : ResponseWriter_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.Start_Element ("label"); UI.Render_Attributes (Context, TEXT_ATTRIBUTE_NAMES, Writer); end if; end Encode_Begin; procedure Encode_End (UI : in UILabel; Context : in out Faces_Context'Class) is Writer : ResponseWriter_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.End_Element ("label"); end if; end Encode_End; type Object_Array is array (Positive range <>) of EL.Objects.Object; package Formats is new Util.Strings.Formats (Stream => Ada.Strings.Unbounded.Unbounded_String, Char => Character, Input => String, Value => EL.Objects.Object, Value_List => Object_Array, Put => Ada.Strings.Unbounded.Append, To_Input => EL.Objects.To_String); procedure Encode_Begin (UI : in UIOutputFormat; Context : in out Faces_Context'Class) is use ASF.Components.Core; begin if not UI.Is_Rendered (Context) then return; end if; declare Params : constant UIParameter_Access_Array := Get_Parameters (UI); Values : 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 => EL.Objects.To_Object (Result)); end; end Encode_Begin; begin Set_Text_Attributes (TEXT_ATTRIBUTE_NAMES); Set_Text_Attributes (LABEL_ATTRIBUTE_NAMES); Set_Interactive_Attributes (LABEL_ATTRIBUTE_NAMES); end ASF.Components.Html.Text;
----------------------------------------------------------------------- -- html -- ASF HTML Components -- 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 EL.Objects; with ASF.Components.Core; with Util.Texts.Formats; 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 value to write on the output. -- ------------------------------ function Get_Value (UI : in UIOutput) return EL.Objects.Object is begin return UI.Get_Attribute (UI.Get_Context.all, "value"); -- return UI.Value; end Get_Value; -- ------------------------------ -- Set the value to write on the output. -- ------------------------------ procedure Set_Value (UI : in out UIOutput; Value : in EL.Objects.Object) is begin UI.Value := Value; end Set_Value; procedure Write_Output (UI : in UIOutput; Context : in out Faces_Context'Class; Value : in EL.Objects.Object) is Writer : constant ResponseWriter_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_Text (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 => UI.Get_Value); end if; end Encode_Begin; procedure Encode_Begin (UI : in UILabel; Context : in out Faces_Context'Class) is Writer : ResponseWriter_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.Start_Element ("label"); UI.Render_Attributes (Context, TEXT_ATTRIBUTE_NAMES, Writer); end if; end Encode_Begin; procedure Encode_End (UI : in UILabel; Context : in out Faces_Context'Class) is Writer : ResponseWriter_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.End_Element ("label"); end if; end Encode_End; type Object_Array is array (Positive range <>) of EL.Objects.Object; package Formats is new Util.Texts.Formats (Stream => Ada.Strings.Unbounded.Unbounded_String, Char => Character, Input => String, Value => EL.Objects.Object, Value_List => Object_Array, Put => Ada.Strings.Unbounded.Append, To_Input => EL.Objects.To_String); procedure Encode_Begin (UI : in UIOutputFormat; Context : in out Faces_Context'Class) is use ASF.Components.Core; begin if not UI.Is_Rendered (Context) then return; end if; declare Params : constant UIParameter_Access_Array := Get_Parameters (UI); Values : 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 => EL.Objects.To_Object (Result)); end; end Encode_Begin; begin Set_Text_Attributes (TEXT_ATTRIBUTE_NAMES); Set_Text_Attributes (LABEL_ATTRIBUTE_NAMES); Set_Interactive_Attributes (LABEL_ATTRIBUTE_NAMES); end ASF.Components.Html.Text;
Update to use the Utils.Texts.Formats generic package
Update to use the Utils.Texts.Formats generic package
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
9429bdecdc2f7bf403b9635723426f50d52c3242
regtests/gen-integration-tests.ads
regtests/gen-integration-tests.ads
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Change the working directory before running dynamo. overriding procedure Set_Up (T : in out Test); -- Restore the working directory after running dynamo. overriding procedure Tear_Down (T : in out Test); -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-model command. procedure Test_Add_Model (T : in out Test); -- Test add-module-operation command. procedure Test_Add_Module_Operation (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-layout command. procedure Test_Add_Layout (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test generate command with Hibernate XML mapping files. procedure Test_Generate_Hibernate (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Bean with inheritance). procedure Test_Generate_XMI_Bean_Table (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Change the working directory before running dynamo. overriding procedure Set_Up (T : in out Test); -- Restore the working directory after running dynamo. overriding procedure Tear_Down (T : in out Test); -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test dynamo create-project command --gtk. procedure Test_Create_GTK_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-model command. procedure Test_Add_Model (T : in out Test); -- Test add-module-operation command. procedure Test_Add_Module_Operation (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-layout command. procedure Test_Add_Layout (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test generate command with Hibernate XML mapping files. procedure Test_Generate_Hibernate (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Bean with inheritance). procedure Test_Generate_XMI_Bean_Table (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
Add a simple test for gtk project generation
Add a simple test for gtk project generation
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
8e9d97cbe91e6922e718dae737345b04162332da
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; with Security.Contexts; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is begin return False; end Has_Permission; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; with Security.Contexts; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Permissions.Permission_Index; begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; end Has_Permission; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
Implement Has_Permission
Implement Has_Permission
Ada
apache-2.0
Letractively/ada-security
938af4e890f814e60430f0194aebb4a96803a635
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. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is begin null; end Add_Policy; procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is begin null; 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. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is begin null; 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;
Implement Add_Permission
Implement Add_Permission
Ada
apache-2.0
stcarrez/ada-security
0b60dd330af7a134cdb5ae2e92e205ab0a8ed3e6
src/os-linux/util-processes-os.ads
src/os-linux/util-processes-os.ads
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams.Raw; with Util.Systems.Os; with Interfaces.C; with Interfaces.C.Strings; private package Util.Processes.Os is SHELL : constant String := "/bin/sh"; type System_Process is new Util.Processes.System_Process with record Argv : Util.Systems.Os.Ptr_Ptr_Array := null; Argc : Interfaces.C.size_t := 0; In_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; Out_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; Err_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; Out_Append : Boolean := False; Err_Append : Boolean := False; end record; -- Wait for the process to exit. overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration); -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15); -- Spawn a new process. overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE); -- Append the argument to the process argument list. overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String); -- Set the process input, output and error streams to redirect and use specified files. overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean); -- Deletes the storage held by the system process. overriding procedure Finalize (Sys : in out System_Process); private -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. function Create_Stream (File : in Util.Systems.Os.File_Type) return Util.Streams.Raw.Raw_Stream_Access; end Util.Processes.Os;
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams.Raw; with Util.Systems.Os; with Interfaces.C; with Interfaces.C.Strings; private package Util.Processes.Os is SHELL : constant String := "/bin/sh"; type System_Process is new Util.Processes.System_Process with record Argv : Util.Systems.Os.Ptr_Ptr_Array := null; Argc : Interfaces.C.size_t := 0; In_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; Out_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; Err_File : Util.Systems.Os.Ptr := Interfaces.C.Strings.Null_Ptr; To_Close : File_Type_Array_Access; Out_Append : Boolean := False; Err_Append : Boolean := False; end record; -- Wait for the process to exit. overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration); -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15); -- Spawn a new process. overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE); -- Append the argument to the process argument list. overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String); -- Set the process input, output and error streams to redirect and use specified files. overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean; To_Close : in File_Type_Array_Access); -- Deletes the storage held by the system process. overriding procedure Finalize (Sys : in out System_Process); private -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. function Create_Stream (File : in Util.Systems.Os.File_Type) return Util.Streams.Raw.Raw_Stream_Access; end Util.Processes.Os;
Add a To_Close parameter to Set_Streams
Add a To_Close parameter to Set_Streams
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4e416728531eca2f7edb2295e654f68c1f4b59a6
mat/src/gtk/mat-events-gtkmat.adb
mat/src/gtk/mat-events-gtkmat.adb
----------------------------------------------------------------------- -- gprofiler-events - Profiler Events Description -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Glib; with Gtk.Handlers; with Gtk.Widget; with Util.Log.Loggers; package body MAT.Events.Gtkmat is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Gtkmat"); package Event_Cb is new Gtk.Handlers.Return_Callback (Gtk.Drawing_Area.Gtk_Drawing_Area_Record, Boolean); Target : Event_Drawing_Type_Access; function Redraw (Area : access Gtk.Drawing_Area.Gtk_Drawing_Area_Record'Class; Cr : in Cairo.Cairo_Context) return Boolean is begin Draw (Target.all, Cr); return False; end Redraw; procedure Create (Drawing : in out Event_Drawing_Type) is begin Target := Drawing'Unrestricted_Access; Gtk.Drawing_Area.Gtk_New (Drawing.Drawing); Event_Cb.Connect (Drawing.Drawing, Gtk.Widget.Signal_Draw, Event_Cb.To_Marshaller (Redraw'Access)); -- , Drawing'Unrestricted_Access); end Create; procedure Draw (Onto : in Event_Drawing_Type; Cr : in Cairo.Cairo_Context) is use type Glib.Gdouble; type Thread_Ref_Array is array (1 .. 10) of MAT.Types.Target_Thread_Ref; Iter : MAT.Events.Targets.Target_Event_Cursor; Threads : Thread_Ref_Array := (others => 0); Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; Time_F : Glib.Gdouble; Thread_F : Glib.Gdouble; function Get_Thread_Index (Thread : in MAT.Types.Target_Thread_Ref) return Natural is begin for I in Thread_Ref_Array'Range loop if Threads (I) = Thread then return I; end if; if Threads (I) = 0 then Threads (I) := Thread; return I; end if; end loop; return Threads'Last; end Get_Thread_Index; function Get_Time_Pos (Time : in MAT.Types.Target_Tick_Ref) return Glib.Gdouble is Dt : constant MAT.Types.Target_Tick_Ref := Time - Start; begin return Time_F * Glib.Gdouble (Dt); end Get_Time_Pos; function Get_Thread_Pos (Thread : in MAT.Types.Target_Thread_Ref) return Glib.Gdouble is Pos : Natural := Get_Thread_Index (Thread); begin return Thread_F * Glib.Gdouble (Pos); end Get_Thread_Pos; Width : Glib.Gint; Height : Glib.Gint; begin Log.Info ("Redraw events window"); Cairo.Translate (Cr, 10.0, 10.0); -- Cairo.Scale (Cr, 10.0, 10.0); if Onto.List.Is_Empty then return; end if; Width := Onto.Drawing.Get_Allocated_Width; Height := Onto.Drawing.Get_Allocated_Height; Start := Onto.List.First_Element.Time; Finish := Onto.List.Last_Element.Time; if Start = Finish then Time_F := 10.0; else Time_F := Glib.Gdouble (Width) / Glib.Gdouble (Finish - Start); end if; Thread_F := Glib.Gdouble (Height) / 10.0; Iter := Onto.List.First; while MAT.Events.Targets.Target_Event_Vectors.Has_Element (Iter) loop declare Event : MAT.Events.Targets.Target_Event := MAT.Events.Targets.Target_Event_Vectors.Element (Iter); Y : Glib.Gdouble := Get_Thread_Pos (Event.Thread); X : Glib.Gdouble := Get_Time_Pos (Event.Time); begin if Event.Event = 4 then Cairo.Set_Source_Rgb (Cr, Red => 0.0, Green => 0.0, Blue => 1.0); else Cairo.Set_Source_Rgb (Cr, Red => 1.0, Green => 0.0, Blue => 0.0); end if; Cairo.Move_To (Cr, X, Y); Cairo.Line_To (Cr, X, Y + 10.0); Cairo.Stroke (Cr); end; MAT.Events.Targets.Target_Event_Vectors.Next (Iter); end loop; -- Cairo.Set_Source_Rgb (Cr, Red => 0.0, Green => 0.0, Blue => 0.0); -- for I in 1 .. 10 loop -- Cairo.Move_To (Cr, 10.0 * Glib.Gdouble (I), 0.0); -- Cairo.Line_To (Cr, 10.0 * Glib.Gdouble (I), 2.0); -- Cairo.Stroke (Cr); -- end loop; end Draw; end MAT.Events.Gtkmat;
----------------------------------------------------------------------- -- gprofiler-events - Profiler Events Description -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Glib; with Gtk.Handlers; with Gtk.Widget; with Util.Log.Loggers; package body MAT.Events.Gtkmat is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Gtkmat"); package Event_Cb is new Gtk.Handlers.Return_Callback (Gtk.Drawing_Area.Gtk_Drawing_Area_Record, Boolean); Target : Event_Drawing_Type_Access; function Redraw (Area : access Gtk.Drawing_Area.Gtk_Drawing_Area_Record'Class; Cr : in Cairo.Cairo_Context) return Boolean is begin Draw (Target.all, Cr); return False; end Redraw; procedure Create (Drawing : in out Event_Drawing_Type) is begin Target := Drawing'Unrestricted_Access; Gtk.Drawing_Area.Gtk_New (Drawing.Drawing); Event_Cb.Connect (Drawing.Drawing, Gtk.Widget.Signal_Draw, Event_Cb.To_Marshaller (Redraw'Access)); -- , Drawing'Unrestricted_Access); end Create; procedure Draw (Onto : in Event_Drawing_Type; Cr : in Cairo.Cairo_Context) is use type Glib.Gdouble; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; type Thread_Ref_Array is array (1 .. 10) of MAT.Types.Target_Thread_Ref; Iter : MAT.Events.Targets.Target_Event_Cursor; Threads : Thread_Ref_Array := (others => 0); Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; Time_F : Glib.Gdouble; Thread_F : Glib.Gdouble; function Get_Thread_Index (Thread : in MAT.Types.Target_Thread_Ref) return Natural is begin for I in Thread_Ref_Array'Range loop if Threads (I) = Thread then return I; end if; if Threads (I) = 0 then Threads (I) := Thread; return I; end if; end loop; return Threads'Last; end Get_Thread_Index; function Get_Time_Pos (Time : in MAT.Types.Target_Tick_Ref) return Glib.Gdouble is Dt : constant MAT.Types.Target_Tick_Ref := Time - Start; begin return Time_F * Glib.Gdouble (Dt); end Get_Time_Pos; function Get_Thread_Pos (Thread : in MAT.Types.Target_Thread_Ref) return Glib.Gdouble is Pos : Natural := Get_Thread_Index (Thread); begin return Thread_F * Glib.Gdouble (Pos); end Get_Thread_Pos; Width : Glib.Gint; Height : Glib.Gint; begin Log.Info ("Redraw events window"); Cairo.Translate (Cr, 10.0, 10.0); -- Cairo.Scale (Cr, 10.0, 10.0); if Onto.List.Is_Empty then return; end if; Width := Onto.Drawing.Get_Allocated_Width; Height := Onto.Drawing.Get_Allocated_Height; Start := Onto.List.First_Element.Time; Finish := Onto.List.Last_Element.Time; if Start = Finish then Time_F := 10.0; else Time_F := Glib.Gdouble (Width) / Glib.Gdouble (Finish - Start); end if; Thread_F := Glib.Gdouble (Height) / 10.0; Iter := Onto.List.First; while MAT.Events.Targets.Target_Event_Vectors.Has_Element (Iter) loop declare Event : MAT.Events.Targets.Target_Event := MAT.Events.Targets.Target_Event_Vectors.Element (Iter); Y : Glib.Gdouble := Get_Thread_Pos (Event.Thread); X : Glib.Gdouble := Get_Time_Pos (Event.Time); begin if Event.Event = 4 then Cairo.Set_Source_Rgb (Cr, Red => 0.0, Green => 0.0, Blue => 1.0); else Cairo.Set_Source_Rgb (Cr, Red => 1.0, Green => 0.0, Blue => 0.0); end if; Cairo.Move_To (Cr, X, Y); Cairo.Line_To (Cr, X, Y + 10.0); Cairo.Stroke (Cr); end; MAT.Events.Targets.Target_Event_Vectors.Next (Iter); end loop; -- Cairo.Set_Source_Rgb (Cr, Red => 0.0, Green => 0.0, Blue => 0.0); -- for I in 1 .. 10 loop -- Cairo.Move_To (Cr, 10.0 * Glib.Gdouble (I), 0.0); -- Cairo.Line_To (Cr, 10.0 * Glib.Gdouble (I), 2.0); -- Cairo.Stroke (Cr); -- end loop; end Draw; end MAT.Events.Gtkmat;
Update to use the MAT.Types.Target_Tick_Ref and Target_Thread_Ref
Update to use the MAT.Types.Target_Tick_Ref and Target_Thread_Ref
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d5bc6bd015395d8b75e9c9b87cbec6cef1c75203
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. ----------------------------------------------------------------------- with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with ASF.Applications; -- == Introduction == -- The <b>AWA.Jobs</b> plugin defines a batch job framework for modules to perform and execute -- long running and deferred actions. -- -- -- == 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); -- -- === 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;
Document the new AWA jobs plugin
Document the new AWA jobs plugin
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
f51694a8f12ec2f99ffae74c23b8e1e74cf8e26b
awa/plugins/awa-votes/src/awa-votes-beans.ads
awa/plugins/awa-votes/src/awa-votes-beans.ads
----------------------------------------------------------------------- -- awa-votes-beans -- Beans for module votes -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with AWA.Votes.Services; with AWA.Votes.Modules; with AWA.Votes.Models; package AWA.Votes.Beans is type Vote_Bean is new AWA.Votes.Models.Vote_Bean with record Service : AWA.Votes.Services.Vote_Service_Access := null; end record; type Vote_Bean_Access is access all Vote_Bean'Class; -- Action to vote up. overriding procedure Vote_Up (Bean : in out Vote_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Action to vote down. overriding procedure Vote_Down (Bean : in out Vote_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Votes_Bean bean instance. function Create_Vote_Bean (Module : in AWA.Votes.Modules.Vote_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Votes.Beans;
----------------------------------------------------------------------- -- awa-votes-beans -- Beans for module votes -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with AWA.Votes.Modules; with AWA.Votes.Models; package AWA.Votes.Beans is type Vote_Bean is new AWA.Votes.Models.Vote_Bean with private; type Vote_Bean_Access is access all Vote_Bean'Class; -- Action to vote up. overriding procedure Vote_Up (Bean : in out Vote_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Action to vote down. overriding procedure Vote_Down (Bean : in out Vote_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Votes_Bean bean instance. function Create_Vote_Bean (Module : in AWA.Votes.Modules.Vote_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; private type Vote_Bean is new AWA.Votes.Models.Vote_Bean with record Module : AWA.Votes.Modules.Vote_Module_Access := null; end record; end AWA.Votes.Beans;
Use the vote module and make the Vote_Bean definition private
Use the vote module and make the Vote_Bean definition private
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
28eccf307c70decf9df1ea0225c59413fbb7295f
regtests/ado-drivers-tests.adb
regtests/ado-drivers-tests.adb
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Test_Caller; with ADO.Statements; with ADO.Databases; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Server", Test_Set_Connection_Server'Access); Caller.Add_Test (Suite, "Test ADO.Databases (Errors)", Test_Empty_Connection'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is pragma Unreferenced (T); begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; -- ------------------------------ -- Test the Set_Server operation. -- ------------------------------ procedure Test_Set_Connection_Server (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Server ("server-name"); Util.Tests.Assert_Equals (T, "server-name", Controller.Get_Server, "Configuration Set_Server returned invalid value"); end Test_Set_Connection_Server; -- ------------------------------ -- Test the connection operations on an empty connection. -- ------------------------------ procedure Test_Empty_Connection (T : in out Test) is use ADO.Databases; C : ADO.Databases.Connection; Stmt : ADO.Statements.Query_Statement; pragma Unreferenced (Stmt); begin T.Assert (ADO.Databases.Get_Status (C) = ADO.Databases.CLOSED, "The database connection must be closed for an empty connection"); Util.Tests.Assert_Equals (T, "null", ADO.Databases.Get_Ident (C), "Get_Ident must return null"); -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, null); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, "select"); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Get_Driver must raise NOT_OPEN. begin T.Assert (ADO.Databases.Get_Driver (C) /= null, "Get_Driver must raise an exception"); exception when NOT_OPEN => null; end; end Test_Empty_Connection; end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Test_Caller; with ADO.Statements; with ADO.Databases; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Server", Test_Set_Connection_Server'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Port", Test_Set_Connection_Port'Access); Caller.Add_Test (Suite, "Test ADO.Databases (Errors)", Test_Empty_Connection'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is pragma Unreferenced (T); begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; -- ------------------------------ -- Test the Set_Server operation. -- ------------------------------ procedure Test_Set_Connection_Server (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Server ("server-name"); Util.Tests.Assert_Equals (T, "server-name", Controller.Get_Server, "Configuration Set_Server returned invalid value"); end Test_Set_Connection_Server; -- ------------------------------ -- Test the Set_Port operation. -- ------------------------------ procedure Test_Set_Connection_Port (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Port (1234); Util.Tests.Assert_Equals (T, 1234, Controller.Get_Port, "Configuration Set_Port returned invalid value"); end Test_Set_Connection_Port; -- ------------------------------ -- Test the connection operations on an empty connection. -- ------------------------------ procedure Test_Empty_Connection (T : in out Test) is use ADO.Databases; C : ADO.Databases.Connection; Stmt : ADO.Statements.Query_Statement; pragma Unreferenced (Stmt); begin T.Assert (ADO.Databases.Get_Status (C) = ADO.Databases.CLOSED, "The database connection must be closed for an empty connection"); Util.Tests.Assert_Equals (T, "null", ADO.Databases.Get_Ident (C), "Get_Ident must return null"); -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, null); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, "select"); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Get_Driver must raise NOT_OPEN. begin T.Assert (ADO.Databases.Get_Driver (C) /= null, "Get_Driver must raise an exception"); exception when NOT_OPEN => null; end; end Test_Empty_Connection; end ADO.Drivers.Tests;
Implement the Test_Set_Connection_Port procedure
Implement the Test_Set_Connection_Port procedure
Ada
apache-2.0
stcarrez/ada-ado
6bd9e062e3ee72b19d1bdd1b3debaa5ad7824909
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 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;
----------------------------------------------------------------------- -- 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.Plugins.Templates; 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; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; 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; Template.Set_Template_Path ("."); -- Open the file and parse it (assume UTF-8). Input.Open (Name, "WCEM=8"); Engine.Set_Plugin_Factory (Template'Unchecked_Access); 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;
Add the file template plugin
Add the file template plugin
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0ac1e3554fa21203ef544b107631d4d469a4305f
src/asf-components-html-pages.adb
src/asf-components-html-pages.adb
----------------------------------------------------------------------- -- html-pages -- HTML Page Components -- Copyright (C) 2011, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Beans.Objects; with ASF.Utils; -- The <b>Pages</b> package implements various components used when building an HTML page. -- package body ASF.Components.Html.Pages is BODY_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; HEAD_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Head Component -- ------------------------------ -- ------------------------------ -- Encode the HTML head element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("head"); UI.Render_Attributes (Context, HEAD_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML head element. Before closing the head, generate the resource -- links that have been queued for the head generation. -- ------------------------------ overriding procedure Encode_End (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("head"); end Encode_End; -- ------------------------------ -- Encode the HTML body element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("body"); UI.Render_Attributes (Context, BODY_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML body element. Before closing the body, generate the inclusion -- of differed resources (pending javascript, inclusion of javascript files) -- ------------------------------ overriding procedure Encode_End (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("body"); end Encode_End; -- ------------------------------ -- Encode the DOCTYPE element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIDoctype; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Write ("<!DOCTYPE "); Writer.Write (UI.Get_Attribute ("rootElement", Context, "")); declare Public : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "public"); System : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "system"); begin if not Util.Beans.Objects.Is_Null (Public) then Writer.Write (" PUBLIC """); Writer.Write (Public); Writer.Write ('"'); end if; if not Util.Beans.Objects.Is_Null (System) then Writer.Write (" """); Writer.Write (System); Writer.Write ('"'); end if; end; Writer.Write ('>'); end if; end Encode_Begin; begin Utils.Set_Head_Attributes (HEAD_ATTRIBUTE_NAMES); Utils.Set_Text_Attributes (BODY_ATTRIBUTE_NAMES); Utils.Set_Body_Attributes (BODY_ATTRIBUTE_NAMES); end ASF.Components.Html.Pages;
----------------------------------------------------------------------- -- html-pages -- HTML Page Components -- Copyright (C) 2011, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Beans.Objects; with ASF.Utils; -- The <b>Pages</b> package implements various components used when building an HTML page. -- package body ASF.Components.Html.Pages is BODY_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; HEAD_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Head Component -- ------------------------------ -- ------------------------------ -- Encode the HTML head element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("head"); UI.Render_Attributes (Context, HEAD_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML head element. Before closing the head, generate the resource -- links that have been queued for the head generation. -- ------------------------------ overriding procedure Encode_End (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("head"); end Encode_End; -- ------------------------------ -- Encode the HTML body element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("body"); UI.Render_Attributes (Context, BODY_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML body element. Before closing the body, generate the inclusion -- of differed resources (pending javascript, inclusion of javascript files) -- ------------------------------ overriding procedure Encode_End (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("body"); end Encode_End; -- ------------------------------ -- Encode the DOCTYPE element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIDoctype; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Write ("<!DOCTYPE "); Writer.Write (UI.Get_Attribute ("rootElement", Context, "")); declare Public : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "public"); System : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "system"); begin if not Util.Beans.Objects.Is_Null (Public) then Writer.Write (" PUBLIC """); Writer.Write (Public); Writer.Write ('"'); end if; if not Util.Beans.Objects.Is_Null (System) then Writer.Write (" """); Writer.Write (System); Writer.Write ('"'); end if; end; Writer.Write ('>'); Writer.Write (ASCII.LF); end if; end Encode_Begin; begin Utils.Set_Head_Attributes (HEAD_ATTRIBUTE_NAMES); Utils.Set_Text_Attributes (BODY_ATTRIBUTE_NAMES); Utils.Set_Body_Attributes (BODY_ATTRIBUTE_NAMES); end ASF.Components.Html.Pages;
Add a newline after the doctype
Add a newline after the doctype
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
b8b518599ca47dd77849e8070149462a7ac11b87
awa/awaunit/awa-tests-helpers-users.adb
awa/awaunit/awa-tests-helpers-users.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with ASF.Principals; with ASF.Tests; with ASF.Responses.Mockup; 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 type AWA.Users.Principals.Principal_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests.Helpers.Users"); MAX_USERS : constant Positive := 10; Logged_Users : array (1 .. MAX_USERS) of AWA.Users.Principals.Principal_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join awa_email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Signup_Kind : constant Integer := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.SIGNUP_KEY); Password_Kind : constant Integer := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.RESET_PASSWORD_KEY); begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ? AND o.kind = ?"); Query.Bind_Param (1, Email); Query.Bind_Param (2, Signup_Kind); Key.Find (DB, Query, Found); if not Found then Query.Bind_Param (2, Password_Kind); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; 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'Class; 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); -- Keep track of the Principal instance so that Tear_Down will release it. -- Most tests will call Login but don't call Logout because there is no real purpose -- for the test in doing that and it allows to keep the unit test simple. This creates -- memory leak because the Principal instance is not freed. for I in Logged_Users'Range loop if Logged_Users (I) = null then Logged_Users (I) := Principal; exit; end if; end loop; end Login; -- ------------------------------ -- Simulate a user login on the request. Upon successful login, a session that is -- authentified is associated with the request object. -- ------------------------------ procedure Login (Email : in String; Request : in out ASF.Requests.Mockup.Request) is User : Test_User; Reply : ASF.Responses.Mockup.Response; begin Create_User (User, Email); ASF.Tests.Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); end Login; -- ------------------------------ -- Setup the context and security context to simulate an anonymous user. -- ------------------------------ procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class; Sec_Context : in out Security.Contexts.Security_Context) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Context.Set_Context (App, null); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => null); end Anonymous; -- ------------------------------ -- Simulate the recovery password process for the given user. -- ------------------------------ procedure Recover_Password (Email : in String) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then Log.Error ("Invalid redirect after lost password"); end if; -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); if not Key.Is_Null then Log.Error ("There is no access key associated with the user"); end if; -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("reset-password", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then Log.Error ("Invalid response"); end if; -- Check that the user is logged and we have a user principal now. if Request.Get_User_Principal = null then Log.Error ("A user principal should be defined"); end if; end; end Recover_Password; overriding procedure Finalize (Principal : in out Test_User) is begin Free (Principal.Principal); end Finalize; -- ------------------------------ -- Cleanup and release the Principal that have been allocated from the Login session -- but not released because the Logout is not called from the unit test. -- ------------------------------ procedure Tear_Down is begin for I in Logged_Users'Range loop if Logged_Users (I) /= null then Free (Logged_Users (I)); end if; end loop; end Tear_Down; end AWA.Tests.Helpers.Users;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with ASF.Principals; with ASF.Tests; with ASF.Responses.Mockup; 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 type AWA.Users.Principals.Principal_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests.Helpers.Users"); MAX_USERS : constant Positive := 10; Logged_Users : array (1 .. MAX_USERS) of AWA.Users.Principals.Principal_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join awa_email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Signup_Kind : constant Integer := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.SIGNUP_KEY); Password_Kind : constant Integer := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.RESET_PASSWORD_KEY); begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ? AND o.kind = ?"); Query.Bind_Param (1, Email); Query.Bind_Param (2, Signup_Kind); Key.Find (DB, Query, Found); if not Found then Query.Bind_Param (2, Password_Kind); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; 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'Class; 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); -- Keep track of the Principal instance so that Tear_Down will release it. -- Most tests will call Login but don't call Logout because there is no real purpose -- for the test in doing that and it allows to keep the unit test simple. This creates -- memory leak because the Principal instance is not freed. for I in Logged_Users'Range loop if Logged_Users (I) = null then Logged_Users (I) := Principal; exit; end if; end loop; end Login; -- ------------------------------ -- Simulate a user login on the request. Upon successful login, a session that is -- authentified is associated with the request object. -- ------------------------------ procedure Login (Email : in String; Request : in out ASF.Requests.Mockup.Request'Class) is User : Test_User; Reply : ASF.Responses.Mockup.Response; begin Create_User (User, Email); ASF.Tests.Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); end Login; -- ------------------------------ -- Setup the context and security context to simulate an anonymous user. -- ------------------------------ procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class; Sec_Context : in out Security.Contexts.Security_Context) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Context.Set_Context (App, null); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => null); end Anonymous; -- ------------------------------ -- Simulate the recovery password process for the given user. -- ------------------------------ procedure Recover_Password (Email : in String) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then Log.Error ("Invalid redirect after lost password"); end if; -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); if not Key.Is_Null then Log.Error ("There is no access key associated with the user"); end if; -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("reset-password", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then Log.Error ("Invalid response"); end if; -- Check that the user is logged and we have a user principal now. if Request.Get_User_Principal = null then Log.Error ("A user principal should be defined"); end if; end; end Recover_Password; overriding procedure Finalize (Principal : in out Test_User) is begin Free (Principal.Principal); end Finalize; -- ------------------------------ -- Cleanup and release the Principal that have been allocated from the Login session -- but not released because the Logout is not called from the unit test. -- ------------------------------ procedure Tear_Down is begin for I in Logged_Users'Range loop if Logged_Users (I) /= null then Free (Logged_Users (I)); end if; end loop; end Tear_Down; end AWA.Tests.Helpers.Users;
Update to allow class wide request for login
Update to allow class wide request for login
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d7e90726f9eae9f4fd552f1876a825f8b2e5cd2b
src/babel-strategies-default.adb
src/babel-strategies-default.adb
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- pragma Ada_2012; with Babel.Files.Signatures; with Util.Encoders.SHA1; package body Babel.Strategies.Default is -- Returns true if there is a directory that must be processed by the current strategy. overriding function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean is begin return false; -- not Strategy.Queue.Directories.Is_Empty; end Has_Directory; -- Get the next directory that must be processed by the strategy. overriding procedure Peek_Directory (Strategy : in out Default_Strategy_Type; Directory : out Babel.Files.Directory_Type) is Last : constant String := ""; -- Strategy.Queue.Directories.Last_Element; begin -- Strategy.Queue.Directories.Delete_Last; null; end Peek_Directory; overriding procedure Execute (Strategy : in out Default_Strategy_Type) is use type Babel.Files.File_Type; Content : Babel.Files.Buffers.Buffer_Access := Strategy.Allocate_Buffer; File : Babel.Files.File_Type; SHA1 : Util.Encoders.SHA1.Hash_Array; begin Strategy.Queue.Queue.Dequeue (File, 1.0); if File = Babel.Files.NO_FILE then Strategy.Release_Buffer (Content); else Strategy.Read_File (File, Content); Babel.Files.Signatures.Sha1 (Content.all, SHA1); Babel.Files.Set_Signature (File, SHA1); if Babel.Files.Is_Modified (File) then Strategy.Backup_File (File, Content); else Strategy.Release_Buffer (Content); end if; end if; exception when others => Strategy.Release_Buffer (Content); raise; end Execute; -- Scan the directory overriding procedure Scan (Strategy : in out Default_Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is procedure Add_Queue (File : in Babel.Files.File_Type) is begin Strategy.Queue.Add_File (File); end Add_Queue; begin Strategy_Type (Strategy).Scan (Directory, Container); Container.Each_File (Add_Queue'Access); end Scan; -- overriding -- procedure Add_File (Into : in out Default_Strategy_Type; -- Path : in String; -- Element : in Babel.Files.File) is -- begin -- Into.Queue.Add_File (Path, Element); -- end Add_File; -- -- overriding -- procedure Add_Directory (Into : in out Default_Strategy_Type; -- Path : in String; -- Name : in String) is -- begin -- Into.Queue.Add_Directory (Path, Name); -- end Add_Directory; end Babel.Strategies.Default;
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- pragma Ada_2012; with Babel.Files.Signatures; with Util.Encoders.SHA1; with Util.Log.Loggers; package body Babel.Strategies.Default is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies.Default"); -- Returns true if there is a directory that must be processed by the current strategy. overriding function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean is begin return false; -- not Strategy.Queue.Directories.Is_Empty; end Has_Directory; -- Get the next directory that must be processed by the strategy. overriding procedure Peek_Directory (Strategy : in out Default_Strategy_Type; Directory : out Babel.Files.Directory_Type) is Last : constant String := ""; -- Strategy.Queue.Directories.Last_Element; begin -- Strategy.Queue.Directories.Delete_Last; null; end Peek_Directory; -- Set the file queue that the strategy must use. procedure Set_Queue (Strategy : in out Default_Strategy_Type; Queue : in Babel.Files.Queues.File_Queue_Access) is begin Strategy.Queue := Queue; end Set_Queue; overriding procedure Execute (Strategy : in out Default_Strategy_Type) is use type Babel.Files.File_Type; Content : Babel.Files.Buffers.Buffer_Access := Strategy.Allocate_Buffer; File : Babel.Files.File_Type; SHA1 : Util.Encoders.SHA1.Hash_Array; begin Strategy.Queue.Queue.Dequeue (File, 10.0); if File = Babel.Files.NO_FILE then Log.Debug ("Dequeue NO_FILE"); Strategy.Release_Buffer (Content); else Log.Debug ("Dequeue {0}", Babel.Files.Get_Path (File)); Strategy.Read_File (File, Content); Babel.Files.Signatures.Sha1 (Content.all, SHA1); Babel.Files.Set_Signature (File, SHA1); if Babel.Files.Is_Modified (File) then Strategy.Backup_File (File, Content); else Strategy.Release_Buffer (Content); end if; end if; exception when others => Strategy.Release_Buffer (Content); raise; end Execute; -- Scan the directory overriding procedure Scan (Strategy : in out Default_Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is procedure Add_Queue (File : in Babel.Files.File_Type) is begin Log.Debug ("Queueing {0}", Babel.Files.Get_Path (File)); Strategy.Queue.Add_File (File); end Add_Queue; begin Strategy_Type (Strategy).Scan (Directory, Container); Container.Each_File (Add_Queue'Access); end Scan; -- overriding -- procedure Add_File (Into : in out Default_Strategy_Type; -- Path : in String; -- Element : in Babel.Files.File) is -- begin -- Into.Queue.Add_File (Path, Element); -- end Add_File; -- -- overriding -- procedure Add_Directory (Into : in out Default_Strategy_Type; -- Path : in String; -- Name : in String) is -- begin -- Into.Queue.Add_Directory (Path, Name); -- end Add_Directory; end Babel.Strategies.Default;
Implement Set_Queue operation Add some logs to track and understand problems
Implement Set_Queue operation Add some logs to track and understand problems
Ada
apache-2.0
stcarrez/babel
66685fca1eb63ec0a5697889397295c09c53a346
awa/regtests/awa-commands-tests.adb
awa/regtests/awa-commands-tests.adb
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Test_Caller; with Util.Log.Loggers; package body AWA.Commands.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands.Tests"); package Caller is new Util.Test_Caller (Test, "Commands"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Commands.Start_Stop", Test_Start_Stop'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (tables)", Test_List_Tables'Access); end Add_Tests; -- ------------------------------ -- Execute the command and get the output in a string. -- ------------------------------ procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0) is P : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; begin if Input'Length > 0 then Log.Info ("Execute: {0} < {1}", Command, Input); elsif Output'Length > 0 then Log.Info ("Execute: {0} > {1}", Command, Output); else Log.Info ("Execute: {0}", Command); end if; P.Set_Input_Stream (Input); P.Set_Output_Stream (Output); P.Open (Command, Util.Processes.READ_ALL); -- Write on the process input stream. Result := Ada.Strings.Unbounded.Null_Unbounded_String; Buffer.Initialize (P'Unchecked_Access, 8192); Buffer.Read (Result); P.Close; Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Result)); Log.Info ("Command result: {0}", Result); Util.Tests.Assert_Equals (T, Status, P.Get_Exit_Status, "Command '" & Command & "' failed"); end Execute; -- ------------------------------ -- Test start and stop command. -- ------------------------------ procedure Test_Start_Stop (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); task Start_Server is entry Start; entry Wait (Result : out Ada.Strings.Unbounded.Unbounded_String); end Start_Server; task body Start_Server is Output : Ada.Strings.Unbounded.Unbounded_String; begin accept Start do null; end Start; begin T.Execute ("bin/awa_command -c " & Config & " start -m 26123", "", "", Output, 0); exception when others => Output := Ada.Strings.Unbounded.To_Unbounded_String ("* exception *"); end; accept Wait (Result : out Ada.Strings.Unbounded.Unbounded_String) do Result := Output; end Wait; end Start_Server; Result : Ada.Strings.Unbounded.Unbounded_String; begin -- Launch the 'start' command in a separate task because the command will hang. Start_Server.Start; delay 5.0; -- Launch the 'stop' command, this should terminate the 'start' command. T.Execute ("bin/awa_command -c " & Config & " stop -m 26123", "", "", Result, 0); -- Wait for the task result. Start_Server.Wait (Result); Util.Tests.Assert_Matches (T, "Starting...", Result, "AWA start command output"); end Test_Start_Stop; procedure Test_List_Tables (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -t", "", "", Result, 0); Util.Tests.Assert_Matches (T, "awa_audit *[0-9]+", Result, "Missing awa_audit"); Util.Tests.Assert_Matches (T, "awa_session *[0-9]+", Result, "Missing awa_session"); Util.Tests.Assert_Matches (T, "entity_type *[0-9]+", Result, "Missing entity_type"); Util.Tests.Assert_Matches (T, "awa_wiki_page *[0-9]+", Result, "Missing awa_wiki_page"); end Test_List_Tables; end AWA.Commands.Tests;
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Test_Caller; with Util.Log.Loggers; package body AWA.Commands.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands.Tests"); package Caller is new Util.Test_Caller (Test, "Commands"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Commands.Start_Stop", Test_Start_Stop'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (tables)", Test_List_Tables'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (users)", Test_List_Users'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (sessions)", Test_List_Sessions'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (jobs)", Test_List_Jobs'Access); end Add_Tests; -- ------------------------------ -- Execute the command and get the output in a string. -- ------------------------------ procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0) is P : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; begin if Input'Length > 0 then Log.Info ("Execute: {0} < {1}", Command, Input); elsif Output'Length > 0 then Log.Info ("Execute: {0} > {1}", Command, Output); else Log.Info ("Execute: {0}", Command); end if; P.Set_Input_Stream (Input); P.Set_Output_Stream (Output); P.Open (Command, Util.Processes.READ_ALL); -- Write on the process input stream. Result := Ada.Strings.Unbounded.Null_Unbounded_String; Buffer.Initialize (P'Unchecked_Access, 8192); Buffer.Read (Result); P.Close; Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Result)); Log.Info ("Command result: {0}", Result); Util.Tests.Assert_Equals (T, Status, P.Get_Exit_Status, "Command '" & Command & "' failed"); end Execute; -- ------------------------------ -- Test start and stop command. -- ------------------------------ procedure Test_Start_Stop (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); task Start_Server is entry Start; entry Wait (Result : out Ada.Strings.Unbounded.Unbounded_String); end Start_Server; task body Start_Server is Output : Ada.Strings.Unbounded.Unbounded_String; begin accept Start do null; end Start; begin T.Execute ("bin/awa_command -c " & Config & " start -m 26123", "", "", Output, 0); exception when others => Output := Ada.Strings.Unbounded.To_Unbounded_String ("* exception *"); end; accept Wait (Result : out Ada.Strings.Unbounded.Unbounded_String) do Result := Output; end Wait; end Start_Server; Result : Ada.Strings.Unbounded.Unbounded_String; begin -- Launch the 'start' command in a separate task because the command will hang. Start_Server.Start; delay 5.0; -- Launch the 'stop' command, this should terminate the 'start' command. T.Execute ("bin/awa_command -c " & Config & " stop -m 26123", "", "", Result, 0); -- Wait for the task result. Start_Server.Wait (Result); Util.Tests.Assert_Matches (T, "Starting...", Result, "AWA start command output"); end Test_Start_Stop; procedure Test_List_Tables (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -t", "", "", Result, 0); Util.Tests.Assert_Matches (T, "awa_audit *[0-9]+", Result, "Missing awa_audit"); Util.Tests.Assert_Matches (T, "awa_session *[0-9]+", Result, "Missing awa_session"); Util.Tests.Assert_Matches (T, "entity_type *[0-9]+", Result, "Missing entity_type"); Util.Tests.Assert_Matches (T, "awa_wiki_page *[0-9]+", Result, "Missing awa_wiki_page"); end Test_List_Tables; -- ------------------------------ -- Test the list -u command. -- ------------------------------ procedure Test_List_Users (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -u", "", "", Result, 0); Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user"); Util.Tests.Assert_Matches (T, "[email protected]", Result, "Missing email"); end Test_List_Users; -- ------------------------------ -- Test the list -s command. -- ------------------------------ procedure Test_List_Sessions (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -s", "", "", Result, 0); Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user"); end Test_List_Sessions; -- ------------------------------ -- Test the list -j command. -- ------------------------------ procedure Test_List_Jobs (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -j", "", "", Result, 0); Util.Tests.Assert_Matches (T, "S_FACTORY", Result, "Missing factory"); Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user"); end Test_List_Jobs; end AWA.Commands.Tests;
Implement Test_List_Users, Test_List_Sessions, Test_List_Jobs procedures
Implement Test_List_Users, Test_List_Sessions, Test_List_Jobs procedures
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5b8582dd2fb86994de542a59ed9fbd0097c5f668
regtests/ado-parameters-tests.adb
regtests/ado-parameters-tests.adb
----------------------------------------------------------------------- -- ado-parameters-tests -- Test query parameters and SQL expansion -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; package body ADO.Parameters.Tests is use Util.Tests; type Dialect is new ADO.Drivers.Dialects.Dialect with null record; -- Check if the string is a reserved keyword. overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean; -- Test the Add_Param operation for various types. generic type T (<>) is private; with procedure Add_Param (L : in out ADO.Parameters.Abstract_List; V : in T) is <>; Value : T; Name : String; procedure Test_Add_Param_T (Tst : in out Test); -- Test the Bind_Param operation for various types. generic type T (<>) is private; with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List; N : in String; V : in T) is <>; Value : T; Name : String; procedure Test_Bind_Param_T (Tst : in out Test); -- Test the Add_Param operation for various types. procedure Test_Add_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Add_Param (ADO.Parameters.Abstract_List (SQL), Value); end loop; Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name); end Test_Add_Param_T; -- Test the Bind_Param operation for various types. procedure Test_Bind_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value); end loop; Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name); end Test_Bind_Param_T; procedure Test_Add_Param_Integer is new Test_Add_Param_T (Integer, Add_Param, 10, "Integer"); procedure Test_Add_Param_Identifier is new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier"); procedure Test_Add_Param_Boolean is new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean"); procedure Test_Add_Param_String is new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String"); procedure Test_Add_Param_Calendar is new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time"); procedure Test_Add_Param_Unbounded_String is new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); procedure Test_Bind_Param_Integer is new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer"); procedure Test_Bind_Param_Identifier is new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier"); procedure Test_Bind_Param_Boolean is new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean"); procedure Test_Bind_Param_String is new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String"); procedure Test_Bind_Param_Calendar is new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time"); procedure Test_Bind_Param_Unbounded_String is new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); package Caller is new Util.Test_Caller (Test, "ADO.Parameters"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Parameters.Expand", Test_Expand_Sql'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)", Test_Expand_Error'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)", Test_Expand_Perf'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)", Test_Add_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)", Test_Add_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)", Test_Add_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)", Test_Add_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)", Test_Add_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)", Test_Add_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)", Test_Bind_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)", Test_Bind_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)", Test_Bind_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)", Test_Bind_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)", Test_Bind_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)", Test_Bind_Param_Unbounded_String'Access); end Add_Tests; -- ------------------------------ -- Check if the string is a reserved keyword. -- ------------------------------ overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean is pragma Unreferenced (D, Name); begin return False; end Is_Reserved; -- ------------------------------ -- Test expand SQL with parameters. -- ------------------------------ procedure Test_Expand_Sql (T : in out Test) is SQL : ADO.Parameters.List; D : aliased Dialect; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin SQL.Set_Dialect (D'Unchecked_Access); SQL.Bind_Param (1, "select '"); SQL.Bind_Param (2, "from"); SQL.Bind_Param ("user_id", String '("23")); SQL.Bind_Param ("object_23_identifier", Integer (44)); SQL.Bind_Param ("bool", True); SQL.Bind_Param (6, False); SQL.Bind_Param ("_date", Ada.Calendar.Clock); SQL.Bind_Null_Param ("_null"); Check ("?", "'select '''"); Check (":2", "'from'"); Check (":6", "0"); Check (":user_id", "'23'"); Check (":bool", "1"); Check (":_null", "NULL"); Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? :2 :user_id :object_23_identifier :bool :6", "select 'select ''' 'from' '23' 44 1 0"); end Test_Expand_Sql; -- ------------------------------ -- Test expand with invalid parameters. -- ------------------------------ procedure Test_Expand_Error (T : in out Test) is SQL : ADO.Parameters.List; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin Check (":<", "<"); Check (":234", ""); Check (":name", ""); Check ("select :", "select :"); end Test_Expand_Error; -- ------------------------------ -- Test expand performance. -- ------------------------------ procedure Test_Expand_Perf (T : in out Test) is pragma Unreferenced (T); SQL : ADO.Parameters.List; D : aliased Dialect; begin SQL.Set_Dialect (D'Unchecked_Access); declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop SQL.Bind_Param (I, I); end loop; Util.Measures.Report (T, "Bind_Param (1000 calls)"); end; declare B : constant Unbounded_String := To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := To_String (B); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand reference To_String"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = :10"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)"); end; end Test_Expand_Perf; end ADO.Parameters.Tests;
----------------------------------------------------------------------- -- ado-parameters-tests -- Test query parameters and SQL expansion -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; package body ADO.Parameters.Tests is use Util.Tests; type Dialect is new ADO.Drivers.Dialects.Dialect with null record; -- Check if the string is a reserved keyword. overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean; -- Test the Add_Param operation for various types. generic type T (<>) is private; with procedure Add_Param (L : in out ADO.Parameters.Abstract_List; V : in T) is <>; Value : T; Name : String; procedure Test_Add_Param_T (Tst : in out Test); -- Test the Bind_Param operation for various types. generic type T (<>) is private; with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List; N : in String; V : in T) is <>; Value : T; Name : String; procedure Test_Bind_Param_T (Tst : in out Test); -- Test the Add_Param operation for various types. procedure Test_Add_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Add_Param (ADO.Parameters.Abstract_List (SQL), Value); end loop; Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name); end Test_Add_Param_T; -- Test the Bind_Param operation for various types. procedure Test_Bind_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value); end loop; Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name); end Test_Bind_Param_T; procedure Test_Add_Param_Integer is new Test_Add_Param_T (Integer, Add_Param, 10, "Integer"); procedure Test_Add_Param_Long_Long_Integer is new Test_Add_Param_T (Long_Long_Integer, Add_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Add_Param_Identifier is new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier"); procedure Test_Add_Param_Boolean is new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean"); procedure Test_Add_Param_String is new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String"); procedure Test_Add_Param_Calendar is new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time"); procedure Test_Add_Param_Unbounded_String is new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); procedure Test_Bind_Param_Integer is new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer"); procedure Test_Bind_Param_Long_Long_Integer is new Test_Bind_Param_T (Long_Long_Integer, Bind_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Bind_Param_Identifier is new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier"); procedure Test_Bind_Param_Entity_Type is new Test_Bind_Param_T (Entity_Type, Bind_Param, 100, "Entity_Type"); procedure Test_Bind_Param_Boolean is new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean"); procedure Test_Bind_Param_String is new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String"); procedure Test_Bind_Param_Calendar is new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time"); procedure Test_Bind_Param_Unbounded_String is new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); package Caller is new Util.Test_Caller (Test, "ADO.Parameters"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Parameters.Expand", Test_Expand_Sql'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)", Test_Expand_Error'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)", Test_Expand_Perf'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)", Test_Add_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)", Test_Add_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Long_Long_Integer)", Test_Add_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)", Test_Add_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)", Test_Add_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)", Test_Add_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)", Test_Add_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)", Test_Bind_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)", Test_Bind_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Long_Long_Integer)", Test_Bind_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)", Test_Bind_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)", Test_Bind_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)", Test_Bind_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)", Test_Bind_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Entity_Type)", Test_Bind_Param_Entity_Type'Access); end Add_Tests; -- ------------------------------ -- Check if the string is a reserved keyword. -- ------------------------------ overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean is pragma Unreferenced (D, Name); begin return False; end Is_Reserved; -- ------------------------------ -- Test expand SQL with parameters. -- ------------------------------ procedure Test_Expand_Sql (T : in out Test) is SQL : ADO.Parameters.List; D : aliased Dialect; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin SQL.Set_Dialect (D'Unchecked_Access); SQL.Bind_Param (1, "select '"); SQL.Bind_Param (2, "from"); SQL.Bind_Param ("user_id", String '("23")); SQL.Bind_Param ("object_23_identifier", Integer (44)); SQL.Bind_Param ("bool", True); SQL.Bind_Param (6, False); SQL.Bind_Param ("_date", Ada.Calendar.Clock); SQL.Bind_Null_Param ("_null"); Check ("?", "'select '''"); Check (":2", "'from'"); Check (":6", "0"); Check (":user_id", "'23'"); Check (":bool", "1"); Check (":_null", "NULL"); Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? :2 :user_id :object_23_identifier :bool :6", "select 'select ''' 'from' '23' 44 1 0"); end Test_Expand_Sql; -- ------------------------------ -- Test expand with invalid parameters. -- ------------------------------ procedure Test_Expand_Error (T : in out Test) is SQL : ADO.Parameters.List; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin Check (":<", "<"); Check (":234", ""); Check (":name", ""); Check ("select :", "select :"); end Test_Expand_Error; -- ------------------------------ -- Test expand performance. -- ------------------------------ procedure Test_Expand_Perf (T : in out Test) is pragma Unreferenced (T); SQL : ADO.Parameters.List; D : aliased Dialect; begin SQL.Set_Dialect (D'Unchecked_Access); declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop SQL.Bind_Param (I, I); end loop; Util.Measures.Report (T, "Bind_Param (1000 calls)"); end; declare B : constant Unbounded_String := To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := To_String (B); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand reference To_String"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = :10"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)"); end; end Test_Expand_Perf; end ADO.Parameters.Tests;
Add tests for Bind_Param/Add_Param for Long_Long_Integer and Entity_Type
Add tests for Bind_Param/Add_Param for Long_Long_Integer and Entity_Type
Ada
apache-2.0
stcarrez/ada-ado
f23f99363059923b903861f9d8309711cb7efea6
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Contexts; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers.URLs; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Perm : constant Security.Controllers.URLs.URL_Controller_Access := new Security.Controllers.URLs.URL_Controller; begin Perm.Manager := Policy'Unchecked_Access; Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Perm.Manager); Policy.Manager.Add_Permission (Name => "url", Permission => Perm.all'Access); end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
Create the URL controller and register it when the URL policy configuration is read
Create the URL controller and register it when the URL policy configuration is read
Ada
apache-2.0
stcarrez/ada-security
04909dd528898fe93609348581b77d3eba6df87b
regtests/util-properties-tests.adb
regtests/util-properties-tests.adb
----------------------------------------------------------------------- -- Util -- Unit tests for properties -- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Ada.Text_IO; with Util.Properties; with Util.Properties.Basic; package body Util.Properties.Tests is use Ada.Text_IO; use type Ada.Containers.Count_Type; use Util.Properties.Basic; -- Test -- Properties.Set -- Properties.Exists -- Properties.Get procedure Test_Property (T : in out Test) is Props : Properties.Manager; begin T.Assert (Exists (Props, "test") = False, "Invalid properties"); Props.Set ("test", "toto"); T.Assert (Exists (Props, "test"), "Property was not inserted"); declare V : constant String := Props.Get ("test"); begin T.Assert (V = "toto", "Property was not set correctly"); end; end Test_Property; -- Test basic properties -- Get -- Set procedure Test_Integer_Property (T : in out Test) is Props : Properties.Manager; V : Integer := 23; begin Integer_Property.Set (Props, "test-integer", V); T.Assert (Props.Exists ("test-integer"), "Invalid properties"); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 23, "Property was not inserted"); Integer_Property.Set (Props, "test-integer", 24); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 24, "Property was not inserted"); V := Integer_Property.Get (Props, "unknown", 25); T.Assert (V = 25, "Default value must be returned for a Get"); end Test_Integer_Property; -- Test loading of property files procedure Test_Load_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 30, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("root.dir")) = ".", "Invalid property 'root.dir'"); T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar", "Invalid property 'console.lib'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Property; -- ------------------------------ -- Test loading of property files -- ------------------------------ procedure Test_Load_Strip_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin -- Load, filter and strip properties Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F, "tomcat.", True); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 3, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("version")) = "0.6", "Invalid property 'root.dir'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Strip_Property; -- ------------------------------ -- Test copy of properties -- ------------------------------ procedure Test_Copy_Property (T : in out Test) is Props : Properties.Manager; begin Props.Set ("prefix.one", "1"); Props.Set ("prefix.two", "2"); Props.Set ("prefix", "Not copied"); Props.Set ("prefix.", "Copied"); declare Copy : Properties.Manager; begin Copy.Copy (From => Props, Prefix => "prefix.", Strip => True); T.Assert (Copy.Exists ("one"), "Property one not found"); T.Assert (Copy.Exists ("two"), "Property two not found"); T.Assert (Copy.Exists (""), "Property '' does not exist."); end; end Test_Copy_Property; procedure Test_Set_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a"); Props1.Set ("a", "d"); Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")), "Wrong property a in props1"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2 := Props1; Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2.Set ("e", "f"); Props2.Set ("c", "g"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment"); T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment"); Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")), "Wrong property c in props1"); end Test_Set_Preserve_Original; procedure Test_Remove_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Props1.Remove ("a"); T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1"); T.Assert (Props2.Exists ("a"), "Property a was removed from props2"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")), "Wrong property a in props1"); end Test_Remove_Preserve_Original; procedure Test_Missing_Property (T : in out Test) is Props : Properties.Manager; V : Unbounded_String; begin T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted"); Props.Set ("a", "b"); T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; end Test_Missing_Property; procedure Test_Load_Ini_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); declare V : Util.Properties.Value; P : Properties.Manager; begin V := Props.Get_Value ("mysqld"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager; begin P := Props.Get ("mysqld"); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); P := Props.Get ("mysqld_safe"); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager with Unreferenced; begin P := Props.Get ("bad"); T.Fail ("No exception raised for Get()"); exception when NO_PROPERTY => null; end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf"); raise; end Test_Load_Ini_Property; procedure Test_Save_Properties (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties"); begin declare Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); Props.Set ("New-Property", "Some-Value"); Props.Remove ("mysqld"); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed"); Props.Save_Properties (Path); end; declare Props : Properties.Manager; V : Util.Properties.Value; P : Properties.Manager; begin Props.Load_Properties (Path => Path); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)"); T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; end Test_Save_Properties; package Caller is new Util.Test_Caller (Test, "Properties"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Properties.Set", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Exists", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)", Test_Missing_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties", Test_Load_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)", Test_Load_Ini_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties", Test_Load_Strip_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Copy", Test_Copy_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign", Test_Set_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove", Test_Remove_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties", Test_Save_Properties'Access); end Add_Tests; end Util.Properties.Tests;
----------------------------------------------------------------------- -- Util -- Unit tests for properties -- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Ada.Text_IO; with Util.Properties; with Util.Properties.Basic; package body Util.Properties.Tests is use Ada.Text_IO; use type Ada.Containers.Count_Type; use Util.Properties.Basic; -- Test -- Properties.Set -- Properties.Exists -- Properties.Get procedure Test_Property (T : in out Test) is Props : Properties.Manager; begin T.Assert (Exists (Props, "test") = False, "Invalid properties"); T.Assert (Exists (Props, +("test")) = False, "Invalid properties"); T.Assert (Props.Is_Empty, "Property manager should be empty"); Props.Set ("test", "toto"); T.Assert (Exists (Props, "test"), "Property was not inserted"); declare V : constant String := Props.Get ("test"); begin T.Assert (V = "toto", "Property was not set correctly"); end; end Test_Property; -- Test basic properties -- Get -- Set procedure Test_Integer_Property (T : in out Test) is Props : Properties.Manager; V : Integer := 23; begin Integer_Property.Set (Props, "test-integer", V); T.Assert (Props.Exists ("test-integer"), "Invalid properties"); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 23, "Property was not inserted"); Integer_Property.Set (Props, "test-integer", 24); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 24, "Property was not inserted"); V := Integer_Property.Get (Props, "unknown", 25); T.Assert (V = 25, "Default value must be returned for a Get"); end Test_Integer_Property; -- Test loading of property files procedure Test_Load_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 30, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("root.dir")) = ".", "Invalid property 'root.dir'"); T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar", "Invalid property 'console.lib'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Property; -- ------------------------------ -- Test loading of property files -- ------------------------------ procedure Test_Load_Strip_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin -- Load, filter and strip properties Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F, "tomcat.", True); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 3, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("version")) = "0.6", "Invalid property 'root.dir'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Strip_Property; -- ------------------------------ -- Test copy of properties -- ------------------------------ procedure Test_Copy_Property (T : in out Test) is Props : Properties.Manager; begin Props.Set ("prefix.one", "1"); Props.Set ("prefix.two", "2"); Props.Set ("prefix", "Not copied"); Props.Set ("prefix.", "Copied"); declare Copy : Properties.Manager; begin Copy.Copy (From => Props, Prefix => "prefix.", Strip => True); T.Assert (Copy.Exists ("one"), "Property one not found"); T.Assert (Copy.Exists ("two"), "Property two not found"); T.Assert (Copy.Exists (""), "Property '' does not exist."); end; end Test_Copy_Property; procedure Test_Set_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a"); Props1.Set ("a", "d"); Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")), "Wrong property a in props1"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2 := Props1; Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2.Set ("e", "f"); Props2.Set ("c", "g"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment"); T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment"); Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")), "Wrong property c in props1"); end Test_Set_Preserve_Original; procedure Test_Remove_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Props1.Remove ("a"); T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1"); T.Assert (Props2.Exists ("a"), "Property a was removed from props2"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")), "Wrong property a in props1"); end Test_Remove_Preserve_Original; procedure Test_Missing_Property (T : in out Test) is Props : Properties.Manager; V : Unbounded_String; begin T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted"); Props.Set ("a", "b"); T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; end Test_Missing_Property; procedure Test_Load_Ini_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); declare V : Util.Properties.Value; P : Properties.Manager; begin V := Props.Get_Value ("mysqld"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager; begin P := Props.Get ("mysqld"); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); P := Props.Get ("mysqld_safe"); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager with Unreferenced; begin P := Props.Get ("bad"); T.Fail ("No exception raised for Get()"); exception when NO_PROPERTY => null; end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf"); raise; end Test_Load_Ini_Property; procedure Test_Save_Properties (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties"); begin declare Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); Props.Set ("New-Property", "Some-Value"); Props.Remove ("mysqld"); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed"); Props.Save_Properties (Path); end; declare Props : Properties.Manager; V : Util.Properties.Value; P : Properties.Manager; begin Props.Load_Properties (Path => Path); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)"); T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; end Test_Save_Properties; package Caller is new Util.Test_Caller (Test, "Properties"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Properties.Set", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Exists", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)", Test_Missing_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties", Test_Load_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)", Test_Load_Ini_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties", Test_Load_Strip_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Copy", Test_Copy_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign", Test_Set_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove", Test_Remove_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties", Test_Save_Properties'Access); end Add_Tests; end Util.Properties.Tests;
Add test for Util.Properties.Exists and Is_Empty
Add test for Util.Properties.Exists and Is_Empty
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b8a8d021b8a902e050a055615c0d66970a66cd0e
src/asf-components-core-views.adb
src/asf-components-core-views.adb
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- 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.Unchecked_Deallocation; with ASF.Events.Phases; with ASF.Components.Base; with ASF.Events.Faces.Actions; with ASF.Applications.Main; package body ASF.Components.Core.Views is use ASF; use EL.Objects; use type Base.UIComponent_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Get the locale to be used when rendering messages in the view. -- If a locale was set explicitly, return it. -- If the view component defines a <b>locale</b> attribute, evaluate and return its value. -- If the locale is empty, calculate the locale by using the request context and the view -- handler. -- ------------------------------ function Get_Locale (UI : in UIView; Context : in Faces_Context'Class) return Util.Locales.Locale is use type Util.Locales.Locale; begin if UI.Locale /= Util.Locales.NULL_LOCALE then return UI.Locale; end if; declare Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Name => "locale", Context => Context); begin -- If the root view does not specify any locale, calculate it from the request. if Util.Beans.Objects.Is_Null (Value) then return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; -- Resolve the locale. If it is not valid, calculate it from the request. declare Name : constant String := Util.Beans.Objects.To_String (Value); Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name); begin if Locale /= Util.Locales.NULL_LOCALE then return Locale; else return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; end; end; end Get_Locale; -- ------------------------------ -- Set the locale to be used when rendering messages in the view. -- ------------------------------ procedure Set_Locale (UI : in out UIView; Locale : in Util.Locales.Locale) is begin UI.Locale := Locale; end Set_Locale; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); if UI.Left_Tree /= null then UI.Left_Tree.Encode_All (Context); end if; end Encode_Begin; -- ------------------------------ -- Encode the end of the view. -- ------------------------------ overriding procedure Encode_End (UI : in UIView; Context : in out Faces_Context'Class) is begin if UI.Right_Tree /= null then UI.Right_Tree.Encode_All (Context); end if; end Encode_End; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then Parent.Queue_Event (Event); else UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end if; end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then UIView'Class (Parent.all).Broadcast (Phase, Context); else -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end if; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Set the component tree that must be rendered before this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_Before_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Left_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Left_Tree := Tree; end Set_Before_View; -- ------------------------------ -- Set the component tree that must be rendered after this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_After_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Right_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Right_Tree := Tree; end Set_After_View; -- ------------------------------ -- Finalize the object. -- ------------------------------ overriding procedure Finalize (UI : in out UIView) is procedure Free is new Ada.Unchecked_Deallocation (Object => Base.UIComponent'Class, Name => Base.UIComponent_Access); begin Free (UI.Left_Tree); Free (UI.Right_Tree); Base.UIComponent (UI).Finalize; end Finalize; -- ------------------------------ -- Set the metadata facet on the UIView component. -- ------------------------------ procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin if UI.Meta /= null then UI.Log_Error ("A <f:metadata> component was already registered."); -- Delete (UI.Meta); end if; Meta.Root := UI'Unchecked_Access; UI.Meta := Meta; UI.Add_Facet (METADATA_FACET_NAME, Meta.all'Access, Tag); end Set_Metadata; -- ------------------------------ -- Decode the request and prepare for the execution for the view action. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; begin ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => UI.Get_Action_Expression (Context)); exception when EL.Expressions.Invalid_Expression => null; end; end Process_Decodes; -- ------------------------------ -- Get the root component. -- ------------------------------ function Get_Root (UI : in UIViewMetaData) return Base.UIComponent_Access is Result : Base.UIComponent_Access := UI.Get_Parent; Parent : Base.UIComponent_Access := Result.Get_Parent; begin while Parent /= null loop Result := Parent; Parent := Parent.Get_Parent; end loop; return Result; end Get_Root; -- ------------------------------ -- Start encoding the UIComponent. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Begin (Context); end Encode_Begin; -- ------------------------------ -- Encode the children of this component. -- ------------------------------ overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Children (Context); end Encode_Children; -- ------------------------------ -- Finish encoding the component. -- ------------------------------ overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_End (Context); end Encode_End; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class) is begin UI.Root.Queue_Event (Event); end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is begin UI.Root.Broadcast (Phase, Context); end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ overriding procedure Clear_Events (UI : in out UIViewMetaData) is begin UI.Root.Clear_Events; end Clear_Events; end ASF.Components.Core.Views;
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- 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.Unchecked_Deallocation; with ASF.Events.Phases; with ASF.Components.Base; with ASF.Events.Faces.Actions; with ASF.Applications.Main; package body ASF.Components.Core.Views is use ASF; use EL.Objects; use type Base.UIComponent_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Get the locale to be used when rendering messages in the view. -- If a locale was set explicitly, return it. -- If the view component defines a <b>locale</b> attribute, evaluate and return its value. -- If the locale is empty, calculate the locale by using the request context and the view -- handler. -- ------------------------------ function Get_Locale (UI : in UIView; Context : in Faces_Context'Class) return Util.Locales.Locale is use type Util.Locales.Locale; begin if UI.Locale /= Util.Locales.NULL_LOCALE then return UI.Locale; end if; declare Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Name => "locale", Context => Context); begin -- If the root view does not specify any locale, calculate it from the request. if Util.Beans.Objects.Is_Null (Value) then return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; -- Resolve the locale. If it is not valid, calculate it from the request. declare Name : constant String := Util.Beans.Objects.To_String (Value); Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name); begin if Locale /= Util.Locales.NULL_LOCALE then return Locale; else return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; end; end; end Get_Locale; -- ------------------------------ -- Set the locale to be used when rendering messages in the view. -- ------------------------------ procedure Set_Locale (UI : in out UIView; Locale : in Util.Locales.Locale) is begin UI.Locale := Locale; end Set_Locale; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); if UI.Left_Tree /= null then UI.Left_Tree.Encode_All (Context); end if; end Encode_Begin; -- ------------------------------ -- Encode the end of the view. -- ------------------------------ overriding procedure Encode_End (UI : in UIView; Context : in out Faces_Context'Class) is begin if UI.Right_Tree /= null then UI.Right_Tree.Encode_All (Context); end if; end Encode_End; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then Parent.Queue_Event (Event); else UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end if; end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then UIView'Class (Parent.all).Broadcast (Phase, Context); else -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end if; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Set the component tree that must be rendered before this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_Before_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Left_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Left_Tree := Tree; end Set_Before_View; -- ------------------------------ -- Set the component tree that must be rendered after this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_After_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Right_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Right_Tree := Tree; end Set_After_View; -- ------------------------------ -- Finalize the object. -- ------------------------------ overriding procedure Finalize (UI : in out UIView) is procedure Free is new Ada.Unchecked_Deallocation (Object => Base.UIComponent'Class, Name => Base.UIComponent_Access); begin Free (UI.Left_Tree); Free (UI.Right_Tree); Base.UIComponent (UI).Finalize; end Finalize; -- ------------------------------ -- Set the metadata facet on the UIView component. -- ------------------------------ procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin if UI.Meta /= null then UI.Log_Error ("A <f:metadata> component was already registered."); -- Delete (UI.Meta); end if; Meta.Root := UI'Unchecked_Access; UI.Meta := Meta; UI.Add_Facet (METADATA_FACET_NAME, Meta.all'Access, Tag); end Set_Metadata; -- ------------------------------ -- Get the input parameter from the submitted context. This operation is called by -- <tt>Process_Decodes</tt> to retrieve the request parameter associated with the component. -- ------------------------------ overriding function Get_Parameter (UI : in UIViewParameter; Context : in Faces_Context'Class) return String is Name : constant String := UI.Get_Attribute ("name", Context); begin if Name'Length > 0 then return Context.Get_Parameter (Name); else return Html.Forms.UIInput (UI).Get_Parameter (Context); end if; end Get_Parameter; -- ------------------------------ -- Decode the request and prepare for the execution for the view action. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; begin ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => UI.Get_Action_Expression (Context)); exception when EL.Expressions.Invalid_Expression => null; end; end Process_Decodes; -- ------------------------------ -- Get the root component. -- ------------------------------ function Get_Root (UI : in UIViewMetaData) return Base.UIComponent_Access is Result : Base.UIComponent_Access := UI.Get_Parent; Parent : Base.UIComponent_Access := Result.Get_Parent; begin while Parent /= null loop Result := Parent; Parent := Parent.Get_Parent; end loop; return Result; end Get_Root; -- ------------------------------ -- Start encoding the UIComponent. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Begin (Context); end Encode_Begin; -- ------------------------------ -- Encode the children of this component. -- ------------------------------ overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Children (Context); end Encode_Children; -- ------------------------------ -- Finish encoding the component. -- ------------------------------ overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_End (Context); end Encode_End; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class) is begin UI.Root.Queue_Event (Event); end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is begin UI.Root.Broadcast (Phase, Context); end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ overriding procedure Clear_Events (UI : in out UIViewMetaData) is begin UI.Root.Clear_Events; end Clear_Events; end ASF.Components.Core.Views;
Implement the Get_Parameter function to support the <f:viewParam> name attribute
Implement the Get_Parameter function to support the <f:viewParam> name attribute
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
2a0dca15098a5ab078e2820024da8599013ddd96
src/os-linux/util-streams-raw.adb
src/os-linux/util-streams-raw.adb
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams (OS specific) -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Raw is use Util.Systems.Os; -- ----------------------- -- Initialize the raw stream to read and write on the given file descriptor. -- ----------------------- procedure Initialize (Stream : in out Raw_Stream; File : in File_Type) is begin if Stream.File /= NO_FILE then raise Ada.IO_Exceptions.Status_Error; end if; Stream.File := File; end Initialize; -- ----------------------- -- Close the stream. -- ----------------------- overriding procedure Close (Stream : in out Raw_Stream) is begin if Stream.File /= NO_FILE then if Close (Stream.File) /= 0 then raise Ada.IO_Exceptions.Device_Error; end if; Stream.File := NO_FILE; end if; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is begin if Write (Stream.File, Buffer'Address, Buffer'Length) < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Res : Ssize_T; begin Res := Read (Stream.File, Into'Address, Into'Length); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; Last := Into'First + Ada.Streams.Stream_Element_Offset (Res) - 1; end Read; -- ----------------------- -- Reposition the read/write file offset. -- ----------------------- procedure Seek (Stream : in out Raw_Stream; Pos : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) is Res : Util.Systems.Types.off_t; begin Res := Sys_Lseek (Stream.File, Pos, Mode); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Seek; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- procedure Finalize (Object : in out Raw_Stream) is begin Close (Object); end Finalize; end Util.Streams.Raw;
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams (OS specific) -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Raw is use Util.Systems.Os; -- ----------------------- -- Initialize the raw stream to read and write on the given file descriptor. -- ----------------------- procedure Initialize (Stream : in out Raw_Stream; File : in File_Type) is begin if Stream.File /= NO_FILE then raise Ada.IO_Exceptions.Status_Error; end if; Stream.File := File; end Initialize; -- ----------------------- -- Close the stream. -- ----------------------- overriding procedure Close (Stream : in out Raw_Stream) is begin if Stream.File /= NO_FILE then if Close (Stream.File) /= 0 then raise Ada.IO_Exceptions.Device_Error; end if; Stream.File := NO_FILE; end if; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is begin if Write (Stream.File, Buffer'Address, Buffer'Length) < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Res : Ssize_T; begin Res := Read (Stream.File, Into'Address, Into'Length); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; Last := Into'First + Ada.Streams.Stream_Element_Offset (Res) - 1; end Read; -- ----------------------- -- Reposition the read/write file offset. -- ----------------------- procedure Seek (Stream : in out Raw_Stream; Pos : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) is use type Util.Systems.Types.off_t; Res : Util.Systems.Types.off_t; begin Res := Sys_Lseek (Stream.File, Pos, Mode); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Seek; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- procedure Finalize (Object : in out Raw_Stream) is begin Close (Object); end Finalize; end Util.Streams.Raw;
Add missing use type Util.Systems.Types.off_t for Seek function (compilation error with gnat 2014 on 32-bit systems)
Add missing use type Util.Systems.Types.off_t for Seek function (compilation error with gnat 2014 on 32-bit systems)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
da47780154ed9a6a913a400c0d822677f29947cb
src/util-strings.ads
src/util-strings.ads
----------------------------------------------------------------------- -- Util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Ada.Strings.Unbounded; with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Hashed_Sets; with Util.Concurrent.Counters; package Util.Strings is pragma Preelaborate; -- Constant string access type Name_Access is access constant String; -- Compute the hash value of the string. function Hash (Key : Name_Access) return Ada.Containers.Hash_Type; -- Returns true if left and right strings are equivalent. function Equivalent_Keys (Left, Right : Name_Access) return Boolean; -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural; -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural; -- Search for the first occurrence of the pattern in the string. function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural; -- Returns Integer'Image (Value) with the possible space stripped. function Image (Value : in Integer) return String; -- Returns Integer'Image (Value) with the possible space stripped. function Image (Value : in Long_Long_Integer) return String; package String_Access_Map is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Name_Access, Hash => Hash, Equivalent_Keys => Equivalent_Keys); package String_Set is new Ada.Containers.Hashed_Sets (Element_Type => Name_Access, Hash => Hash, Equivalent_Elements => Equivalent_Keys); -- String reference type String_Ref is private; -- Create a string reference from a string. function To_String_Ref (S : in String) return String_Ref; -- Create a string reference from an unbounded string. function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref; -- Get the string function To_String (S : in String_Ref) return String; -- Get the string as an unbounded string function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String; -- Compute the hash value of the string reference. function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type; -- Returns true if left and right string references are equivalent. function Equivalent_Keys (Left, Right : in String_Ref) return Boolean; function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean; -- Returns the string length. function Length (S : in String_Ref) return Natural; private pragma Inline (To_String_Ref); pragma Inline (To_String); type String_Record (Len : Natural) is limited record Counter : Util.Concurrent.Counters.Counter; Str : String (1 .. Len); end record; type String_Record_Access is access all String_Record; type String_Ref is new Ada.Finalization.Controlled with record Str : String_Record_Access := null; end record; -- Increment the reference counter. overriding procedure Adjust (Object : in out String_Ref); -- Decrement the reference counter and free the allocated string. overriding procedure Finalize (Object : in out String_Ref); end Util.Strings;
----------------------------------------------------------------------- -- Util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Ada.Strings.Unbounded; with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Hashed_Sets; with Util.Concurrent.Counters; package Util.Strings is pragma Preelaborate; -- Constant string access type Name_Access is access constant String; -- Compute the hash value of the string. function Hash (Key : Name_Access) return Ada.Containers.Hash_Type; -- Returns true if left and right strings are equivalent. function Equivalent_Keys (Left, Right : Name_Access) return Boolean; -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural; -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural; -- Search for the first occurrence of the pattern in the string. function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural; -- Returns Integer'Image (Value) with the possible space stripped. function Image (Value : in Integer) return String; -- Returns Integer'Image (Value) with the possible space stripped. function Image (Value : in Long_Long_Integer) return String; package String_Access_Map is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Name_Access, Hash => Hash, Equivalent_Keys => Equivalent_Keys); package String_Set is new Ada.Containers.Hashed_Sets (Element_Type => Name_Access, Hash => Hash, Equivalent_Elements => Equivalent_Keys); -- String reference type String_Ref is private; -- Create a string reference from a string. function To_String_Ref (S : in String) return String_Ref; -- Create a string reference from an unbounded string. function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref; -- Get the string function To_String (S : in String_Ref) return String; -- Get the string as an unbounded string function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String; -- Compute the hash value of the string reference. function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type; -- Returns true if left and right string references are equivalent. function Equivalent_Keys (Left, Right : in String_Ref) return Boolean; function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean; -- Returns the string length. function Length (S : in String_Ref) return Natural; private pragma Inline (To_String_Ref); pragma Inline (To_String); type String_Record (Len : Natural) is limited record Counter : Util.Concurrent.Counters.Counter; Str : String (1 .. Len); end record; type String_Record_Access is access all String_Record; type String_Ref is new Ada.Finalization.Controlled with record Str : String_Record_Access := null; end record; pragma Finalize_Storage_Only (String_Ref); -- Increment the reference counter. overriding procedure Adjust (Object : in out String_Ref); -- Decrement the reference counter and free the allocated string. overriding procedure Finalize (Object : in out String_Ref); end Util.Strings;
Add Finalize_Storage_Only on String_Ref
Add Finalize_Storage_Only on String_Ref
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6e63c7a0837d18ac238358f40bf833e96b7cb63a
src/util-properties-factories.adb
src/util-properties-factories.adb
----------------------------------------------------------------------- -- factories -- Factory for property manager implementation -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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 Util.Properties.Hash; package body Util.Properties.Factories is Property_Manager_Factory : Interface_P.Manager_Factory; -- ------------------------------ -- Initialize the property manager by setting the implementation. -- ------------------------------ procedure Initialize (Properties : in out Manager) is use Interface_P; begin if Properties.Impl = null then if Property_Manager_Factory = null then Properties.Impl := new Util.Properties.Hash.Manager; else Properties.Impl := Property_Manager_Factory.all; end if; Properties.Impl.Count := 1; end if; end Initialize; -- ------------------------------ -- Set the default implementation factory for property manager. -- ------------------------------ procedure Set_Default_Factory (Factory : Interface_P.Manager_Factory) is begin Property_Manager_Factory := Factory; end Set_Default_Factory; end Util.Properties.Factories;
----------------------------------------------------------------------- -- factories -- Factory for property manager implementation -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.Hash; package body Util.Properties.Factories is Property_Manager_Factory : Interface_P.Manager_Factory; -- ------------------------------ -- Initialize the property manager by setting the implementation. -- ------------------------------ procedure Initialize (Properties : in out Manager) is use Interface_P; begin if Properties.Impl = null then if Property_Manager_Factory = null then Properties.Impl := new Util.Properties.Hash.Manager; else Properties.Impl := Property_Manager_Factory.all; end if; Util.Concurrent.Counters.Increment (Properties.Impl.Count); end if; end Initialize; -- ------------------------------ -- Set the default implementation factory for property manager. -- ------------------------------ procedure Set_Default_Factory (Factory : Interface_P.Manager_Factory) is begin Property_Manager_Factory := Factory; end Set_Default_Factory; end Util.Properties.Factories;
Update to use the concurrent counter
Update to use the concurrent counter
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
253cf608a8cf76eb3390dedfdd51301c0726bd3f
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Nodes; -- == Wiki Parsers == -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax configured -- on the wiki engine. The document reader operations are invoked while parsing the wiki -- text. procedure Parse (Engine : in out Parser; Text : in Wide_Wide_String; Into : in Wiki.Documents.Document_Reader_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private use Ada.Strings.Wide_Wide_Unbounded; HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is tagged limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Syntax : Wiki_Syntax_Type; Document : Wiki.Nodes.Document; Filters : Wiki.Filters.Filter_Type_Access; -- Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Wiki.Strings.BString (512); Token : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wide_Wide_Character); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wide_Wide_Character); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wide_Wide_Character); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wide_Wide_String) return Boolean; procedure Start_Element (P : in out Parser; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (P : in out Parser; Tag : in Wiki.Nodes.Html_Tag_Type); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Nodes; -- == Wiki Parsers == -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax configured -- on the wiki engine. The document reader operations are invoked while parsing the wiki -- text. procedure Parse (Engine : in out Parser; Text : in Wide_Wide_String; Into : in Wiki.Documents.Document_Reader_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private use Ada.Strings.Wide_Wide_Unbounded; HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is tagged limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Syntax : Wiki_Syntax_Type; Document : Wiki.Nodes.Document; Filters : Wiki.Filters.Filter_Type_Access; -- Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Wiki.Strings.BString (512); Token : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wide_Wide_Character); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wide_Wide_Character); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wide_Wide_Character); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wide_Wide_String) return Boolean; procedure Start_Element (P : in out Parser; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type); procedure End_Element (P : in out Parser; Tag : in Wiki.Nodes.Html_Tag_Type); end Wiki.Parsers;
Update Start_Element to allow changing the attributes
Update Start_Element to allow changing the attributes
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b2e5e51f1db45f48dd816e31eb5578047ed84668
regtests/util-listeners-tests.adb
regtests/util-listeners-tests.adb
----------------------------------------------------------------------- -- util-listeners-tests -- Unit tests for listeners -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Measures; with Util.Test_Caller; with Util.Listeners.Observers; with Util.Listeners.Lifecycles; package body Util.Listeners.Tests is use Util.Tests; Test_Error : exception; Count : Natural := 0; package String_Observers is new Util.Listeners.Observers (String); package Integer_Observers is new Util.Listeners.Observers (Integer); type String_Listener is new String_Observers.Observer with record Expect : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Update (Listener : in String_Listener; Item : in String); type Integer_Listener is new Integer_Observers.Observer with record Expect : Integer; end record; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer); package Caller is new Util.Test_Caller (Test, "Listeners"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Listeners.Publish", Test_Publish'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Publish_Perf", Test_Publish_Perf'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Lifecycles", Test_Lifecycles'Access); end Add_Tests; overriding procedure Update (Listener : in String_Listener; Item : in String) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; -- ------------------------------ -- Test the listeners and the publish operation. -- ------------------------------ procedure Test_Publish (T : in out Test) is Listeners : Util.Listeners.List; L1 : aliased String_Listener; L2 : aliased Integer_Listener; L3 : aliased Integer_Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); Listeners.Append (L3'Unchecked_Access); L1.Expect := Ada.Strings.Unbounded.To_Unbounded_String ("Hello"); String_Observers.Notify (Listeners, "Hello"); Util.Tests.Assert_Equals (T, 1, Count, "Invalid number of calls"); L2.Expect := 3; L3.Expect := 3; Integer_Observers.Notify (Listeners, 3); end Test_Publish; -- ------------------------------ -- Performance test for the listeners. -- ------------------------------ procedure Test_Publish_Perf (T : in out Test) is procedure Test_Basic (Item : in Integer); Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; procedure Test_Basic (Item : in Integer) is begin Util.Tests.Assert_Equals (T, 3, Item); end Test_Basic; begin Listeners.Append (L1'Unchecked_Access); L1.Expect := 3; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Integer_Observers.Notify (Listeners, 3); end loop; Util.Measures.Report (S, "Observers.Notify", 1000); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Test_Basic (3); end loop; Util.Measures.Report (S, "Call basic procedure", 1000); end; end Test_Publish_Perf; -- ------------------------------ -- Test the lifecycles listener. -- ------------------------------ procedure Test_Lifecycles (T : in out Test) is package TL is new Util.Listeners.Lifecycles (Util.Measures.Stamp); Create_Count : Natural := 0; Update_Count : Natural := 0; Delete_Count : Natural := 0; type Listener is new TL.Listener with null record; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp); -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Create_Count := Create_Count + 1; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Update_Count := Update_Count + 1; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Delete_Count := Delete_Count + 1; end On_Delete; Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; L2 : aliased Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); declare S : Util.Measures.Stamp; begin TL.Notify_Create (Listeners, S); TL.Notify_Update (Listeners, S); TL.Notify_Delete (Listeners, S); Util.Measures.Report (S, "Notify Create, Update, Delete"); end; Util.Tests.Assert_Equals (T, 1, Create_Count, "On_Create not called"); Util.Tests.Assert_Equals (T, 1, Update_Count, "On_Update not called"); Util.Tests.Assert_Equals (T, 1, Delete_Count, "On_Delete not called"); end Test_Lifecycles; end Util.Listeners.Tests;
----------------------------------------------------------------------- -- util-listeners-tests -- Unit tests for listeners -- Copyright (C) 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 Ada.Strings.Unbounded; with Util.Measures; with Util.Test_Caller; with Util.Listeners.Observers; with Util.Listeners.Lifecycles; package body Util.Listeners.Tests is Test_Error : exception; Count : Natural := 0; package String_Observers is new Util.Listeners.Observers (String); package Integer_Observers is new Util.Listeners.Observers (Integer); type String_Listener is new String_Observers.Observer with record Expect : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Update (Listener : in String_Listener; Item : in String); type Integer_Listener is new Integer_Observers.Observer with record Expect : Integer; end record; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer); package Caller is new Util.Test_Caller (Test, "Listeners"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Listeners.Publish", Test_Publish'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Publish_Perf", Test_Publish_Perf'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Lifecycles", Test_Lifecycles'Access); end Add_Tests; overriding procedure Update (Listener : in String_Listener; Item : in String) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer) is begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; -- ------------------------------ -- Test the listeners and the publish operation. -- ------------------------------ procedure Test_Publish (T : in out Test) is Listeners : Util.Listeners.List; L1 : aliased String_Listener; L2 : aliased Integer_Listener; L3 : aliased Integer_Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); Listeners.Append (L3'Unchecked_Access); L1.Expect := Ada.Strings.Unbounded.To_Unbounded_String ("Hello"); String_Observers.Notify (Listeners, "Hello"); Util.Tests.Assert_Equals (T, 1, Count, "Invalid number of calls"); L2.Expect := 3; L3.Expect := 3; Integer_Observers.Notify (Listeners, 3); end Test_Publish; -- ------------------------------ -- Performance test for the listeners. -- ------------------------------ procedure Test_Publish_Perf (T : in out Test) is procedure Test_Basic (Item : in Integer); Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; procedure Test_Basic (Item : in Integer) is begin Util.Tests.Assert_Equals (T, 3, Item); end Test_Basic; begin Listeners.Append (L1'Unchecked_Access); L1.Expect := 3; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Integer_Observers.Notify (Listeners, 3); end loop; Util.Measures.Report (S, "Observers.Notify", 1000); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Test_Basic (3); end loop; Util.Measures.Report (S, "Call basic procedure", 1000); end; end Test_Publish_Perf; -- ------------------------------ -- Test the lifecycles listener. -- ------------------------------ procedure Test_Lifecycles (T : in out Test) is package TL is new Util.Listeners.Lifecycles (Util.Measures.Stamp); Create_Count : Natural := 0; Update_Count : Natural := 0; Delete_Count : Natural := 0; type Listener is new TL.Listener with null record; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp); -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Create_Count := Create_Count + 1; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Update_Count := Update_Count + 1; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Delete_Count := Delete_Count + 1; end On_Delete; Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; L2 : aliased Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); declare S : Util.Measures.Stamp; begin TL.Notify_Create (Listeners, S); TL.Notify_Update (Listeners, S); TL.Notify_Delete (Listeners, S); Util.Measures.Report (S, "Notify Create, Update, Delete"); end; Util.Tests.Assert_Equals (T, 1, Create_Count, "On_Create not called"); Util.Tests.Assert_Equals (T, 1, Update_Count, "On_Update not called"); Util.Tests.Assert_Equals (T, 1, Delete_Count, "On_Delete not called"); end Test_Lifecycles; end Util.Listeners.Tests;
Remove unecessary use clauses
Remove unecessary use clauses
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3c9614de9b78fa7b0a7d8db8dd78eb3cd4e18fba
src/ado.ads
src/ado.ads
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams; with Ada.Calendar; with Util.Refs; with Util.Nullables; package ADO is type Int64 is range -2**63 .. 2**63 - 1; for Int64'Size use 64; type Unsigned64 is mod 2**64; for Unsigned64'Size use 64; DEFAULT_TIME : constant Ada.Calendar.Time; -- ------------------------------ -- Database Identifier -- ------------------------------ -- type Identifier is range -2**47 .. 2**47 - 1; NO_IDENTIFIER : constant Identifier := -1; type Entity_Type is range 0 .. 2**16 - 1; NO_ENTITY_TYPE : constant Entity_Type := 0; type Object_Id is record Id : Identifier; Kind : Entity_Type; end record; pragma Pack (Object_Id); -- ------------------------------ -- Nullable Types -- ------------------------------ -- Most database allow to store a NULL instead of an actual integer, date or string value. -- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value. -- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null -- or not. subtype Nullable_Boolean is Util.Nullables.Nullable_Boolean; function "=" (Left, Right : in Nullable_Boolean) return Boolean renames Util.Nullables."="; Null_Boolean : constant Nullable_Boolean; -- An integer which can be null. subtype Nullable_Integer is Util.Nullables.Nullable_Integer; function "=" (Left, Right : in Nullable_Integer) return Boolean renames Util.Nullables."="; Null_Integer : constant Nullable_Integer; -- A string which can be null. subtype Nullable_String is Util.Nullables.Nullable_String; Null_String : constant Nullable_String; -- A date which can be null. subtype Nullable_Time is Util.Nullables.Nullable_Time; Null_Time : constant Nullable_Time; -- Return True if the two nullable times are identical (both null or both same time). function "=" (Left, Right : in Nullable_Time) return Boolean; type Nullable_Entity_Type is record Value : Entity_Type := 0; Is_Null : Boolean := True; end record; Null_Entity_Type : constant Nullable_Entity_Type; -- ------------------------------ -- Blob data type -- ------------------------------ -- The <b>Blob</b> type is used to represent database blobs. The data is stored -- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member. -- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents -- a reference to the blob data. This is intended to minimize data copy. type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record Data : Ada.Streams.Stream_Element_Array (1 .. Len); end record; type Blob_Access is access all Blob; package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access); subtype Blob_Ref is Blob_References.Ref; -- Create a blob with an allocated buffer of <b>Size</b> bytes. function Create_Blob (Size : in Natural) return Blob_Ref; -- Create a blob initialized with the given data buffer. function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref; -- Create a blob initialized with the content from the file whose path is <b>Path</b>. -- Raises an IO exception if the file does not exist. function Create_Blob (Path : in String) return Blob_Ref; -- Return a null blob. function Null_Blob return Blob_Ref; private DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); Null_Boolean : constant Nullable_Boolean := Nullable_Boolean '(Is_Null => True, Value => False); Null_Integer : constant Nullable_Integer := Nullable_Integer '(Is_Null => True, Value => 0); Null_String : constant Nullable_String := Nullable_String '(Is_Null => True, Value => Ada.Strings.Unbounded.Null_Unbounded_String); Null_Time : constant Nullable_Time := Nullable_Time '(Is_Null => True, Value => DEFAULT_TIME); Null_Entity_Type : constant Nullable_Entity_Type := Nullable_Entity_Type '(Is_Null => True, Value => 0); end ADO;
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 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 Ada.Streams; with Ada.Calendar; with Util.Refs; with Util.Nullables; package ADO is type Int64 is range -2**63 .. 2**63 - 1; for Int64'Size use 64; type Unsigned64 is mod 2**64; for Unsigned64'Size use 64; DEFAULT_TIME : constant Ada.Calendar.Time; -- ------------------------------ -- Database Identifier -- ------------------------------ -- type Identifier is range -2**47 .. 2**47 - 1; NO_IDENTIFIER : constant Identifier := -1; type Entity_Type is range 0 .. 2**16 - 1; NO_ENTITY_TYPE : constant Entity_Type := 0; type Object_Id is record Id : Identifier; Kind : Entity_Type; end record; pragma Pack (Object_Id); -- ------------------------------ -- Nullable Types -- ------------------------------ -- Most database allow to store a NULL instead of an actual integer, date or string value. -- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value. -- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null -- or not. subtype Nullable_Boolean is Util.Nullables.Nullable_Boolean; function "=" (Left, Right : in Nullable_Boolean) return Boolean renames Util.Nullables."="; Null_Boolean : constant Nullable_Boolean; -- An integer which can be null. subtype Nullable_Integer is Util.Nullables.Nullable_Integer; function "=" (Left, Right : in Nullable_Integer) return Boolean renames Util.Nullables."="; Null_Integer : constant Nullable_Integer; -- A string which can be null. subtype Nullable_String is Util.Nullables.Nullable_String; Null_String : constant Nullable_String; -- A date which can be null. subtype Nullable_Time is Util.Nullables.Nullable_Time; Null_Time : constant Nullable_Time; -- Return True if the two nullable times are identical (both null or both same time). function "=" (Left, Right : in Nullable_Time) return Boolean; type Nullable_Entity_Type is record Value : Entity_Type := 0; Is_Null : Boolean := True; end record; Null_Entity_Type : constant Nullable_Entity_Type; -- ------------------------------ -- Blob data type -- ------------------------------ -- The <b>Blob</b> type is used to represent database blobs. The data is stored -- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member. -- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents -- a reference to the blob data. This is intended to minimize data copy. type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record Data : Ada.Streams.Stream_Element_Array (1 .. Len); end record; type Blob_Access is access all Blob; package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access); subtype Blob_Ref is Blob_References.Ref; subtype Blob_Accessor is Blob_References.Element_Accessor; -- Create a blob with an allocated buffer of <b>Size</b> bytes. function Create_Blob (Size : in Natural) return Blob_Ref; -- Create a blob initialized with the given data buffer. function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref; -- Create a blob initialized with the content from the file whose path is <b>Path</b>. -- Raises an IO exception if the file does not exist. function Create_Blob (Path : in String) return Blob_Ref; -- Return a null blob. function Null_Blob return Blob_Ref; private DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); Null_Boolean : constant Nullable_Boolean := Nullable_Boolean '(Is_Null => True, Value => False); Null_Integer : constant Nullable_Integer := Nullable_Integer '(Is_Null => True, Value => 0); Null_String : constant Nullable_String := Nullable_String '(Is_Null => True, Value => Ada.Strings.Unbounded.Null_Unbounded_String); Null_Time : constant Nullable_Time := Nullable_Time '(Is_Null => True, Value => DEFAULT_TIME); Null_Entity_Type : constant Nullable_Entity_Type := Nullable_Entity_Type '(Is_Null => True, Value => 0); end ADO;
Add subtype Blob_Accessor
Add subtype Blob_Accessor
Ada
apache-2.0
stcarrez/ada-ado
e2660386b537362a389e473bfa6f59030dbf7b28
src/asf-servlets-files.adb
src/asf-servlets-files.adb
----------------------------------------------------------------------- -- asf.servlets.files -- Static file servlet -- 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 Util.Files; with Util.Streams; with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Directories; with ASF.Streams; package body ASF.Servlets.Files is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out File_Servlet; Context : in Servlet_Registry'Class) is Dir : constant String := Context.Get_Init_Parameter ("web.dir"); begin Server.Dir := new String '(Dir); end Initialize; -- ------------------------------ -- 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 File_Servlet; Requet : in Requests.Request'Class) return Ada.Calendar.Time is begin return Ada.Calendar.Clock; end Get_Last_Modified; -- ------------------------------ -- 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 File_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use Util.Files; URI : constant String := Request.Get_Request_URI; Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all); begin if not Ada.Directories.Exists (Path) or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File then Response.Send_Error (Responses.SC_NOT_FOUND); return; end if; declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Input : Util.Streams.Files.File_Stream; begin Input.Open (Name => Path, Mode => In_File); Util.Streams.Copy (From => Input, Into => Output); end; end Do_Get; end ASF.Servlets.Files;
----------------------------------------------------------------------- -- asf.servlets.files -- Static file servlet -- 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 Util.Files; with Util.Streams; with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Directories; with ASF.Streams; package body ASF.Servlets.Files is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out File_Servlet; Context : in Servlet_Registry'Class) is Dir : constant String := Context.Get_Init_Parameter ("web.dir"); begin Server.Dir := new String '(Dir); end Initialize; -- ------------------------------ -- 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 File_Servlet; Requet : in Requests.Request'Class) return Ada.Calendar.Time is begin return Ada.Calendar.Clock; end Get_Last_Modified; -- ------------------------------ -- 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 File_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use Util.Files; URI : constant String := Request.Get_Path_Info; Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all); begin if not Ada.Directories.Exists (Path) or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File then Response.Send_Error (Responses.SC_NOT_FOUND); return; end if; declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Input : Util.Streams.Files.File_Stream; begin Input.Open (Name => Path, Mode => In_File); Util.Streams.Copy (From => Input, Into => Output); end; end Do_Get; end ASF.Servlets.Files;
Use Get_Path_Info instead of the Get_Request_URI to get only the relative part of the Path and drop the servlet prefix. This path is then used to find the file path.
Use Get_Path_Info instead of the Get_Request_URI to get only the relative part of the Path and drop the servlet prefix. This path is then used to find the file path.
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
51c5496035dfc68828bc9bec337ae08eab1cbd1e
src/util-properties-factories.adb
src/util-properties-factories.adb
----------------------------------------------------------------------- -- factories -- Factory for property manager implementation -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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 Util.Properties.Hash; package body Util.Properties.Factories is Property_Manager_Factory : Interface_P.Manager_Factory; -- ------------------------------ -- Initialize the property manager by setting the implementation. -- ------------------------------ procedure Initialize (Properties : in out Manager) is use Interface_P; begin if Properties.Impl = null then if Property_Manager_Factory = null then Properties.Impl := new Util.Properties.Hash.Manager; else Properties.Impl := Property_Manager_Factory.all; end if; Properties.Impl.Count := 1; end if; end Initialize; -- ------------------------------ -- Set the default implementation factory for property manager. -- ------------------------------ procedure Set_Default_Factory (Factory : Interface_P.Manager_Factory) is begin Property_Manager_Factory := Factory; end Set_Default_Factory; end Util.Properties.Factories;
----------------------------------------------------------------------- -- factories -- Factory for property manager implementation -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.Hash; package body Util.Properties.Factories is Property_Manager_Factory : Interface_P.Manager_Factory; -- ------------------------------ -- Initialize the property manager by setting the implementation. -- ------------------------------ procedure Initialize (Properties : in out Manager) is use Interface_P; begin if Properties.Impl = null then if Property_Manager_Factory = null then Properties.Impl := new Util.Properties.Hash.Manager; else Properties.Impl := Property_Manager_Factory.all; end if; Util.Concurrent.Counters.Increment (Properties.Impl.Count); end if; end Initialize; -- ------------------------------ -- Set the default implementation factory for property manager. -- ------------------------------ procedure Set_Default_Factory (Factory : Interface_P.Manager_Factory) is begin Property_Manager_Factory := Factory; end Set_Default_Factory; end Util.Properties.Factories;
Update to use the concurrent counter
Update to use the concurrent counter
Ada
apache-2.0
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util